Monday, August 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to generate this Spring-boot API documentation example?

Posted: 23 Aug 2021 08:09 AM PDT

I'm trying to track down how some Java Spring-boot API was generated by a developer who has since left the company. The document looks like this:

enter image description here

We have swagger, but this doesn't look like anything generated from that. Definitely doesn't look like javadoc. Any ideas?

Fake data for django channels unit tests

Posted: 23 Aug 2021 08:09 AM PDT

I previously asked a question regarding this topic but finally I gave up on that because there seemed to be no way ...

But now I really really really need to write unit tests for my django channel consumers because the application is growing larger in size and manual testing isn't efficient anymore. So I decided to ask another question and this time I'm going to do my best to explain the situation.

The main problem is "Generating Fake Data". I'm using factory_boy and faker together in order to generate fake data for my tests. When I generate fake data, it is accessible from inside the TestCase itself but is not accessible inside the consumer. Let me show you by an example, consider the code below:

test_consumers.py

from chat.models import PersonalChatRoom  from users.models import User  from django.test import TestCase  from channels.testing import WebsocketCommunicator  from asgiref.sync import sync_to_async  from users.tests.test_setup import TestUtilsMixin  from astra_backend.asgi import application  from chat.tests.model_factory import PersonalChatRoomFactory      class TestPersonalChatRoomConsumer(TestCase, TestUtilsMixin):      def setUp(self) -> None:          super().setUp()          self.chat_room = PersonalChatRoomFactory()          self.u1 = self.chat_room.user_1          self.u2 = self.chat_room.user_2       -> print("setup: (user): ", User.objects.all())       -> print("setup: (personal chat room): ", PersonalChatRoom.objects.all())        async def test_personal_chat_room_connection(self):       -> await sync_to_async(print)("test (user): ", User.objects.all())       -> await sync_to_async(print)("test (personal chat room): ", PersonalChatRoom.objects.all())            com = WebsocketCommunicator(application, f'chat/personal/{self.chat_room.pk}/')          connected, _ = await com.connect()          self.assertTrue(connected)  

consumers.py

...  class PersonalChatConsumer(          ChatRoomManagementMixin,          MessageManagementMixin,          JsonWebsocketConsumer      ):      message_serializer_class = PersonalMessageSerializer      chat_room_class = PersonalChatRoom        def connect(self):       -> print("consumer (user): ", User.objects.all())       -> print("consumer (personal chat room): ", PersonalChatRoom.objects.all())          return super().connect() # some magic here            ...  

output

I'm printing out the contents of the database in 3 different sections of the code:

  • inside the setUp method in the TestPersonalChatRoomConsumer class
  • inside the test_personal_chat_room_connection method in the TestPersonalChatRoomConsumer class
  • inside the connect method of the consumer

I expected the results to be identical but here is the real output when running the test:

setup: (user):  <QuerySet [<User: joshua03@cervantes.net>, <User: pgolden@cummings.com>]>  setup: (personal chat room):  <QuerySet [<PersonalChatRoom: PV joshua03@cervantes.net and pgolden@cummings.com>]>  test (user):  <QuerySet [<User: joshua03@cervantes.net>, <User: pgolden@cummings.com>]>  test (personal chat room):  <QuerySet [<PersonalChatRoom: PV joshua03@cervantes.net and pgolden@cummings.com>]>  ...  consumer (user):  <QuerySet []> # There are no users in the database  consumer (personal chat room):  <QuerySet []> # There are no chat rooms in the database  

Why isn't the data generated inside setUp method accessible inside the consumer?

Here is what I think causes the problem personally:

  • there might be something wrong with database transactions
  • maybe it is about database connections
  • maybe the consumer is using another database

if you need more information please leave a comment down below. I will provide all of them as soon as possible. Thank you all.

How to write a security rule in firestore that queries a document property

Posted: 23 Aug 2021 08:09 AM PDT

I have a document called report stored in my DB on firestore. In the report document I store a userID property that stores the ID of the user that created this document. I also store a reportID in this object which is the same ID that firestore assigns it when the document is created.

I want to write a firestore rule that only allows an authenticated user to access reports that contain the userID.

This is what I have so far:

rules_version = '2';  service cloud.firestore {    match /databases/{database}/documents {      match /reports/{report} {          allow read, write: if request.auth != null &&           request.auth.uid == report.userID;      }    }  }  

The problem is that firebase won't let me access the userID by using the report wildcard like this: report.userID

I must be using the wildcard wrong. I know that {report} should represent any report document inside the reports collection. But it appears I can't query the userID property in that document.

What can I do?

convert json to a pythondataframe

Posted: 23 Aug 2021 08:09 AM PDT

I have a json file which looks like this:

{"parents": ["jobs", "Test Job (torque mode)", "parts", 65], "flanges": [{"bolts": [{"cycles": [{"opData": [{"operator": "admin", "passed": true, "warnMessage": "Passed", "torqueTarget": 336, "angle": 68, "eradMessage": true, "timeStamps": "2021-08-14 10:59:42"}], "status": 0.0, "toolId": "E15552", "streamData": [[]]}, {"opData": [{"operator": "admin", "passed": true, "warnMessage": "Passed", "torqueTarget": 598, "angle": 1, "eradMessage": true, "timeStamps": "2021-08-14 11:05:17"}], "status": 50.0, "toolId": "E15042", "streamData": [{"time": [0.026, 0.052, 0.078, 0.107, 0.133, 0.159, 0.185, 0.211, 0.237, 0.263, 0.289, 0.315, 0.341, 0.367, 0.393, 0.419, 0.445, 0.471, 0.497, 0.523, 0.549, 0.575, 0.601, 0.627, 0.653, 0.679, 0.705, 0.731, 0.757, 0.783, 0.809, 0.835, 0.861, 0.887, 0.913, 0.939, 0.965, 0.991, 1.017, 1.043, 1.069, 1.095, 1.121, 1.147, 1.173, 1.199, 1.225, 1.251, 1.277, 1.303, 1.329, 1.355, 1.381, 1.407, 1.433, 1.459, 1.485, 1.511, 1.537], "torque": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 94, 198, 202, 207, 277, 317, 409, 456, 548, 592, 595, 595, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598, 598], "angle": [0, 0, 0, 1, 3, 4, 7, 10, 13, 15, 17, 20, 23, 26, 27, 30, 33, 36, 38, 40, 43, 46, 49, 50, 53, 56, 58, 59, 59, 59, 59, 59, 59, 60, 60, 60, 60, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61, 61]}]}  

I need help in converting this to a dataframe. When I use this code,

df = pd.read_json(r"C:\Users\rukmani\Dropbox\My PC (jayanth)\Desktop\intomachines data\result_data_torque.json")  

I get this error:

ValueError: arrays must all be same length    

Could someone please help me with this and also converting this to a datafrarme?

Pandas shift datetimeindex takes too long time running

Posted: 23 Aug 2021 08:09 AM PDT

I have a running time issue with shifting a large dataframe with datetime index.

Example using created dummy data:

df = pd.DataFrame({'col1':[0,1,2,3,4,5,6,7,8,9,10,11,12,13]*10**5,'col3':list(np.random.randint(0,100000,14*10**5)),'col2':list(pd.date_range('2020-01-01','2020-08-01',freq='M'))*2*10**5})  df.col3=df.col3.astype(str)  df.drop_duplicates(subset=['col3','col2'],keep='first',inplace=True)  

If I shift not using datetime, it only takes about 12s:

%%time  tmp=df.groupby('col3')['col1'].shift(2,fill_value=0)  Wall time: 12.5 s  

But when I use index datetime, as that situation that I need, it takes about 40 minutes:

%%time      tmp=df.set_index('col2').groupby('col3')['col1'].shift(2,freq='M',fill_value=0)  Wall time: 40min 25s  

In my situation, I need the data from shift(1) until shift(6) and merge them with original data by col2 and col3. So I use for looping and merge. Is there any solution for this? Thanks for your answer, will appreciate so much any respond.

Android PdfDocument multiple pages with Koltin

Posted: 23 Aug 2021 08:09 AM PDT

I am creating pdf of my data using pdfDocument but I am able to create single page only.. Sometimes I am passing 1000 of data which needs multiple pages but I am unable to figure out how can I create next page once reaching the end of first page..

Here is my code :

object PDFGenerator {      private const val TAG = "PDFGenerator"      var pageHeight = 1120      var pagewidth = 792        var logoHeight = 50      var logoWidth = 50        fun generatePDF(context: Context,          headerBuilder: HeaderBuilder,          outputFileName: String = "GeneratedPDF",          logo: Bitmap,          tableTitle: TableTitleBuilder,          valueList: MutableList<TableValuesBuilder>) {            val pdfDocument = PdfDocument()          Log.d(TAG, "generatePDF: starting")            val paint = Paint()          val title = Paint()            val pageInfo = PageInfo.Builder(pagewidth, pageHeight, 100).create()          val myPage = pdfDocument.startPage(pageInfo)            val canvas: Canvas = myPage.canvas          val scaledLogo = Bitmap.createScaledBitmap(logo, logoWidth, logoHeight, false);          canvas.drawBitmap(scaledLogo, 56F, 40F, paint)            /**           * Configuring PDF Header           */          title.textSize = 26F          title.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)          title.color = ContextCompat.getColor(context, R.color.brandTitle)          canvas.drawText(headerBuilder.title, 120F, 65F, title)          title.textSize = 18F          title.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)          title.color = ContextCompat.getColor(context, R.color.brandSubTitle)          canvas.drawText(headerBuilder.subTitle, 120F, 85F, title)            /**           * Configuring table titles           */          var xTitlePos = 50F          val yTitlePos = 150F          title.typeface = Typeface.defaultFromStyle(Typeface.BOLD)          title.color = ContextCompat.getColor(context, R.color.titleText)          title.textSize = 25F          canvas.drawText(tableTitle.name1, xTitlePos, yTitlePos, title)          xTitlePos += 200F          canvas.drawText(tableTitle.name2, xTitlePos, yTitlePos, title)          xTitlePos += 200F          canvas.drawText(tableTitle.name3, xTitlePos, yTitlePos, title)          xTitlePos += 200F          canvas.drawText(tableTitle.name4, xTitlePos, yTitlePos, title)            /**           * Inserting values in table           */          var xValuePos = 50F          var yValuePos = 185F          title.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)          title.color = ContextCompat.getColor(context, R.color.valueText)          title.textSize = 25F          valueList.forEach {              canvas.drawText(it.value1, xValuePos, yValuePos, title)              xValuePos += 200F              canvas.drawText(it.value2, xValuePos, yValuePos, title)              xValuePos += 200F              canvas.drawText(it.value3, xValuePos, yValuePos, title)              xValuePos += 200F              canvas.drawText(it.value4, xValuePos, yValuePos, title)              xValuePos = 50F              yValuePos += 30F          }            pdfDocument.finishPage(myPage)          val file = File(Environment.getExternalStorageDirectory(), "$outputFileName.pdf")          Log.d(TAG, "generatePDF: $file")          try {              pdfDocument.writeTo(FileOutputStream(file))              Toast.makeText(context, "PDF file generated successfully.", Toast.LENGTH_SHORT).show()          } catch (e: IOException) {              e.printStackTrace()          }          pdfDocument.close()          Log.d(TAG, "generatePDF: ending")      }  }  

how I can generate next page once reaching the end of current page..

Thanks in Advance.

Import JavaScript Library and use it as component

Posted: 23 Aug 2021 08:09 AM PDT

I'm trying to use a JavaScript Library (this one) in my Vue project.

But I don't know how to import it, I want to use it as a component if it's possible.

I tried something like this but don't seem to be working for me, maybe I'm doing something wrong?

I want at the end use it like this or anything similar to this:

<div id="toolbar">    <a data-wysihtml5-command="bold">bold</a>    <a data-wysihtml5-command="italic">italic</a>    <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1">H1</a>    <a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="p">P</a>  </div>    <!-- element to edit -->  <div id="editor" data-placeholder="Go on, start editing..."></div>  

Website has different content than reading in a python request

Posted: 23 Aug 2021 08:09 AM PDT

I try to read https://koniewyscigowe.pl/wyscig?w=14222-tor-partynice-nagroda-cheval-francais website by Python script.

My code

web_content = requests.get('https://koniewyscigowe.pl/wyscig?w=14222-tor-partynice-nagroda-cheval-francais')  soup = BeautifulSoup(web_content.text)  for index, table in enumerate(soup.find_all('div', {'class': 'table-responsive'})):      if index == 0:          pass      elif index == 1:          for starts_stats in table.tbody.find_all('tr'):              print('HERE WE ARE')  

During running this code i get error AttributeError: 'NoneType' object has no attribute 'find_all' Object table.tbody is empty. So I can not find any tbody section in second div class="table-responsive". When I check how table looks like before generating an error

<div class="table-responsive">  <table class="table table-striped table-bordered">  <thead>  <tr>  <th style="text-align:center"></th>  <th style="text-align:center">rekord</th>  <th style="text-align:center">koń</th>  <th style="text-align:center">wiek</th>  <th style="text-align:center">powozacy</th>  <th style="text-align:center">trener</th>  <th style="text-align:center">wygrana</th>  </tr>  </thead>  <tr>  <td style="text-align:center">1</td>  <td style="text-align:center">1'29.30"</td>  <td style="text-align:center"><a href="/horse/171-ukamaya-verderie">Ukamaya Verderie</a></td>  <td style="text-align:center">6</td>  <td style="text-align:center"><a href="/dzokej?d=71-robert-kieniksman">pow. R. Kieniksman</a></td>  <td style="text-align:center"><a href="/trener?t=6-andrzej&amp;najderski">A. Najderski</a></td>  <td style="text-align:center">7 000 zł</td>  </tr>  ...  </table>  </div>  

It doesn't have tbody section. But when I checked source of webiste I can see it.

QUESTION: Why table doesn't see tbody? [1]

Adding missing values in Python dictionary

Posted: 23 Aug 2021 08:09 AM PDT

I currently have a dictionary with a numerical index as keys. I know how much values I should have in total in the dictionary and would like to add the missing keys and a null value with those keys in the dictionary. To illustrate I included this example:

dictionary = {'0' : '101', '1' : '102', '2' : '100', '4' : '100.5', '6' : '103'}  

I know that I have 8 values in my dictionary and so I would like to write a function that turns the above dictionary into:

dictionary = {'0' : '101', '1' : '102', '2' : '100', '3' : None, '4' : '100.5', '5' : None, '6' : '103', '7' : None}  

Anyone that knows how to achieve this? Thanks in advance.

How to encode special HTML character without HTML entities in Java

Posted: 23 Aug 2021 08:09 AM PDT

I want to encode only HTML characters not entities.

For example, I want to contert:

<div>1 < 2</div>  

to

<div>1 &lt; 2</div>  

I try StringEscapeUtils but it transforms all to

&lt;div&gt;1 &lt; 2&lt;/div&gt;  

What is the difference between given two lines of dynamic memory allocation in C++ ? Do they both create 10 sized array?

Posted: 23 Aug 2021 08:09 AM PDT

int *arr = new int(10);    int *arr = new int[10];  

It is the code of dynamic memory allocation in c++. But I am not getting What is the difference between these two.

Active when scrolled to its section

Posted: 23 Aug 2021 08:09 AM PDT

I am trying to have this percentage progress bar active when the user have scrolled to its section, currently it moves as soon as you refresh the page or click on the url.

<svg viewBox="0 0 36 36" class="circular-chart orange">    <path class="circle-bg"      d="M18 2.0845        a 15.9155 15.9155 0 0 1 0 31.831        a 15.9155 15.9155 0 0 1 0 -31.831"    />    <path class="circle"      stroke-dasharray="29, 100"      d="M18 2.0845        a 15.9155 15.9155 0 0 1 0 31.831        a 15.9155 15.9155 0 0 1 0 -31.831"    />    <text x="18" y="20.35" class="percentage">29%</text>  </svg>    .circular-chart {   display: block;   margin: 10px auto;   max-width: 80%;   max-height: 250px;  }    .circle-bg {   fill: none;   stroke: #eee;   stroke-width: 3.8;  }    .circle {   fill: none;   stroke-width: 2.8;   stroke-linecap: round;   animation: progress 1s ease-out forwards;  }    @keyframes progress {  0% {   stroke-dasharray: 0 100;     }   }    .circular-chart.orange .circle {   stroke: #ea5031;   }    .percentage {   fill: #666;   font-family: sans-serif;   font-size: 0.5em;   text-anchor: middle;   }   

Node: Sending a request once, but getting to outputs?

Posted: 23 Aug 2021 08:09 AM PDT

const http = require('http')  const server = http.createServer((req, res) => {      res.setHeader('Content-Type', 'text/plain')      console.log('Incoming')      res.write("Hello world, request granted!")      res.end()  })    server.listen(3000, 'localhost', () => {      console.log("Listening for requests on port 3000")  })  

Whenever I start the server, it says "Listening for requests on port 3000", thats correct. But when I open the localhost:3000 on Chrome, it puts out "Incoming" TWO TIMES. Why two times? :D I don't get it.

How to take input in typescript?

Posted: 23 Aug 2021 08:09 AM PDT

I am taking user input for the addition of two numbers in typescript using following code:

 function rotatedString(S1,S2){      return S1+S2;  }        function processData() {          //INPUT[uncomment & modify if required]      var temp = gets().trim('\n').split('\n');          var S1 = temp[0];          var S2 = temp[1];                    //OUTPUT[uncomment & modify if required]          console.log(rotatedString(S1,S2));      }      processData();  

It throws me following error on : https://www.typescriptlang.org/

Parameter 'S1' implicitly has an 'any' type. Parameter 'S2' implicitly has an 'any' type. Cannot find name 'gets'.

Please help me out to take user input in TypeScript

Extend multilevel dataframe using existing index name with reindex Pandas

Posted: 23 Aug 2021 08:09 AM PDT

The objective is deepen existing multiindex df.

Such that, given a df as below

                                     col1      col2  mylevelA_caseA__VAR_A   bar one -1.012046  0.808332  mylevelA_caseA__VAR_B   bar two -0.558629 -0.358550  mylevelA_caseB__VAR_A   baz one  1.514448 -1.045073  mylevelA_caseB__VAR_B   baz two  1.268511 -1.100705  mylevelB_caseC__VAR_C   foo one -2.108172 -1.694602  mylevelB_caseC__VAR_C_D foo two -0.629493 -0.005071  mylevelB_caseC__VAR_E   qux one  0.596771 -0.964429  mylevelB_caseD__VAR_A   qux two  0.257154 -0.248278  

I would like to extend the multilevel index into something like.

enter image description here

At this stage, please note that at the first index level, there are double __ before keyword VAR.

To achieve something similar to the figure above, the following code is drafted

import pandas as pd  import numpy as np  arrays = [["mylevelA_caseA__VAR_A", "mylevelA_caseA__VAR_B", "mylevelA_caseB__VAR_A",             "mylevelA_caseB__VAR_B", "mylevelB_caseC__VAR_C", "mylevelB_caseC__VAR_C_D",             "mylevelB_caseC__VAR_E", "mylevelB_caseD__VAR_A"],            ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],    ["one", "two", "one", "two", "one", "two", "one", "two"]]      df = pd.DataFrame(np.random.randn(8, 2), index=arrays,columns=['col1','col2'])  # print(df)    idx_ls=df.index.values.tolist()  new_multiindex=[]  for x in idx_ls:      b=x[0]      vv=b.split('_')      c=[]      new_data=[]      mvar=[]      for xx in vv:          if not c:              if xx:                  new_data.append(xx)              else:                  c=1          else:              if xx:                  mvar.append(xx)          ntuple=(*new_data,"_ ".join(mvar),*x )      new_multiindex.append(ntuple)      t=1    df=df.reindex(ne    w_multiindex,copy=True)  print(df)  

Which produced

                                                          col1  col2  mylevelA caseA VAR_ A    mylevelA_caseA__VAR_A   bar one   NaN   NaN                 VAR_ B    mylevelA_caseA__VAR_B   bar two   NaN   NaN           caseB VAR_ A    mylevelA_caseB__VAR_A   baz one   NaN   NaN                 VAR_ B    mylevelA_caseB__VAR_B   baz two   NaN   NaN  mylevelB caseC VAR_ C    mylevelB_caseC__VAR_C   foo one   NaN   NaN                 VAR_ C_ D mylevelB_caseC__VAR_C_D foo two   NaN   NaN                 VAR_ E    mylevelB_caseC__VAR_E   qux one   NaN   NaN           caseD VAR_ A    mylevelB_caseD__VAR_A   qux two   NaN   NaN  

There are two issue.

First: the col1 and col2 return nan

Second: May I know whether there is more compact way to minimise the line of code within the for loop.

Qt PostgreSQL foreign key issue

Posted: 23 Aug 2021 08:09 AM PDT

I've created a table which is called user_parameters in Qt Creator. While I was trying to give a reference to another table which is cities. I faced with a syntax error. My snippet for using foreign key and error are given bellow. How can I solve this error? Thx for your helping.

QSqlQuery query;  query.exec("CREATE TABLE user_parameters "                    "(id SERIAL primary key, "                    "firstname varchar(50), "                    "lastname varchar(50), "                    "age integer, "                    "username varchar(50), "                    "password varchar(100), "                    "cityID integer references cities(id))");  

QSqlQuery insertQuery;  int last_id = maxIdValue() + 1;    insertQuery.prepare("INSERT INTO user_parameters (id, firstname, lastname, age, username, password, cityID)"                              "VALUES(:id, :firstname, :lastname, :age, :username, :password, :cityID)");    insertQuery.bindValue(":id", last_id);  insertQuery.bindValue(":firstname", fName);  insertQuery.bindValue(":lastname", lName);  insertQuery.bindValue(":age", age);  insertQuery.bindValue(":username", userName);  insertQuery.bindValue(":password", password);  insertQuery.bindValue(":cityID", cityID);  

QSqlError("42601", "QPSQL: Unable to create query", "ERROR: syntax error at or near "("\nLINE 1: EXECUTE (1, 'Name', 'Surname', 22, 'userName', 'password', 1)\n ^\n(42601)")

How to declare that a Typescript function returns the type of a named property?

Posted: 23 Aug 2021 08:09 AM PDT

I want to input the name of an interface property, and return something which has the type of that property. Is that possible? For example:

interface FooInterface {    x: number;    y: string;  }    function fooFunction(data: FooInterface, name: keyof FooInterface) {    return data[name];  }    let fooVar = fooFunction({ x: 123, y: "hello" }, "x"); // <- Is it possible to make this smart enough to understand that fooVar is now a number?  

how to get count in linq with group by and where clause

Posted: 23 Aug 2021 08:09 AM PDT

I am trying to get the data from 4 tables, table R, RP, P, and S

Table R joins table RP in R_id, Table RP joins table S in P_id Table S joins table P in p_id

I wanna get the count of table R for each P.id in S table but I have a problem that in table RP the P.id is duplicated

my Linq Query :

  int count = (from R in _context.R       join RP in _context.RP on R.id equal RP.R_id      join S in _context.S on RP.P_id equal S.P_id      where S.Route = "input from User"       select R).Count();  

sample date:-

Table R:

id name
1 R1
2 R2
3 R3

Table P:

id name
1 P1
2 P2

Table RP:

id p_id R_id
1 1 1
2 1 2
3 1 3

Table S:

id p_id Route
1 1 Route1
2 1 Route1
3 1 Route1

the Count should be 3 but I got 9 instead

Finding Cells With Only Spaces

Posted: 23 Aug 2021 08:09 AM PDT

I am trying to find any cells with just spaces in. When I run this though it finds cells that are blanks too. Is there anyway to just find cells with spaces?

For i = 1 to lastRow  If len(trim(this workbook.sheets("data").range("a" & i)) = 0 then  Msgbox("a" & i " contains only space")  End if  Next i  

Bind Data not shown in grid

Posted: 23 Aug 2021 08:09 AM PDT

In the below code, I am successfully getting 369 records in the options list:

  public ArrayList GetOptionsChain(string ticker)  {      ticker = CorrectSymbol(ticker);      string url;      if (ticker.StartsWith("^"))          url = string.Format(@"http://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbol={0}&instrument=OPTIDX&date=-", ticker.TrimStart(new char[] { '^' }));      else          url = string.Format(@"http://npg.veh.mybluehostin.me:8000/symbols/?name={0}", ticker.TrimStart(new char[] { '^' }));        ArrayList options_list = new ArrayList();      try      {          XDocument xml = XDocument.Load(url);            var nodes1 = (from n in xml.Descendants("oc").Descendants("row")                        select new                        {                            type = (string)n.Element("type").Value,                            symbol = (string)n.Element("symbol").Value,                            expiration = (string)n.Element("expiration").Value,                            strike = (string)n.Element("strike").Value,                            bid = (string)n.Element("bid").Value,                            ask = (string)n.Element("ask").Value,                            last = (string)n.Element("last").Value,                            change = (string)n.Element("change").Value,                            totalvol = (string)n.Element("totalvol").Value,                            open_int = (string)n.Element("open_int").Value,                            chng_open_int = (string)n.Element("chng_open_int").Value                        }).ToList();                  foreach (var n in nodes1)          {              Option option = new Option();                // option stock ticker and number of stocks per contract              option.stock = ticker;              option.stocks_per_contract = 1;              option.update_timestamp = DateTime.Now;              option.type = n.type;              // symbol              option.symbol = n.symbol; //"." + symbol_href.Replace("javascript:chartPopup(", "").Replace(");", "").Replace(" ", "").Replace(",", "").Replace(".", "").Replace("'", "");                // expiration date              DateTime.TryParse(n.expiration, ci, DateTimeStyles.None, out option.expiration);                // strike price              double.TryParse(n.strike, NumberStyles.Number, ci, out option.strike);                // option bid price                                  option.price.bid = double.NaN;              double.TryParse(n.bid, NumberStyles.Number, ci, out option.price.bid);                // option ask price                option.price.ask = double.NaN;              double.TryParse(n.ask, NumberStyles.Number, ci, out option.price.ask);                // option last price                option.price.last = double.NaN;              double.TryParse(n.last, NumberStyles.Number, ci, out option.price.last);                // option price change                option.price.change = double.NaN;              double.TryParse(n.change, NumberStyles.Number, ci, out option.price.change);                // option volume                option.volume.total = 0;              double.TryParse(n.totalvol, NumberStyles.Number, ci, out option.volume.total);                // open int                option.open_int = 0;              int.TryParse(n.open_int, NumberStyles.Number, ci, out option.open_int);                options_list.Add(option);          }        }      catch (Exception ex)      {        }        return options_list;    }  

But, it won't load the data on grid. The below code is used to show data on screen:

private void UpdateOptionsTable(string stock, Quote quote)      {           // get stock's option list          ArrayList list = Comm.Server.GetOptionsChain(stock);          if (list == null || list.Count == 0) return;            // begin data load          OptionsTable.BeginLoadData();            try          {              foreach (Option option in list)              {                  // update time-value                  if (quote != null) option.price.timevalue = Algo.Model.TimeValue(quote.price.last, option);                    // add option to table                  AddOptionEntry(quote, option);              }          }          catch { }            // end data load          OptionsTable.EndLoadData();      }  

This is the addoptionentry definition:

private OptionsTableRow GetOptionsTableRow()      {          if(OptionsTable.Rows.Count == 0)          {              OptionsTableRow row = OptionsTable.NewOptionsTableRow();              OptionsTable.Rows.Add(row);              row.AcceptChanges();          }            return (OptionsTableRow)OptionsTable.Rows[0];      }  private void AddOptionEntry(Quote quote, Option option)      {          bool new_row = false;          OptionsTableRow row = GetOptionsTableRow();            // make sure the option is in the future          //if (option.expiration > DateTime.Now.AddDays(-3)) return;            if (!OptionsTable.Rows.Contains(option.symbol))          {              row = GetOptionsTableRow();              new_row = true;                try              {                  row.Symbol = option.symbol;              }              catch { }          }          else          {              row = OptionsTable.FindBySymbol(option.symbol);              row.BeginEdit();          }            try          {              row.Type = option.type;              row.Strike = option.strike;              row.Expiration = DateTime.Parse(option.expiration.ToShortDateString());                if (!double.IsNaN(option.price.last)) row.Last = option.price.last;              else row.SetLastNull();                if (!double.IsNaN(option.price.change)) row.Change = option.price.change;              else row.SetChangeNull();                if (!double.IsNaN(option.price.timevalue)) row.TimeValue = option.price.timevalue;              else row.SetTimeValueNull();                if (!double.IsNaN(option.price.bid)) row.Bid = option.price.bid;              else row.SetBidNull();                if (!double.IsNaN(option.price.ask)) row.Ask = option.price.ask;              else row.SetAskNull();                row.Volume = option.volume.total;              row.OpenInt = option.open_int;              row.Stock = option.stock;              row.UpdateTimeStamp = option.update_timestamp;              row.StocksPerContract = option.stocks_per_contract;                if (option.type == "Call")              {                  if (option.strike > quote.price.last * 1.02) row.TheMoney = "OTM";                  else if (option.strike < quote.price.last * 0.98) row.TheMoney = "ITM";                  else if (option.strike == quote.price.last) row.TheMoney = "ATM";                  else if (option.strike > quote.price.last) row.TheMoney = "ATM,OTM";                  else if (option.strike < quote.price.last) row.TheMoney = "ATM,ITM";              }              else              {                  if (option.strike > quote.price.last * 1.02) row.TheMoney = "ITM";                  else if (option.strike < quote.price.last * 0.98) row.TheMoney = "OTM";                  else if (option.strike == quote.price.last) row.TheMoney = "ATM";                  else if (option.strike > quote.price.last) row.TheMoney = "ATM,ITM";                  else if (option.strike < quote.price.last) row.TheMoney = "ATM,OTM";              }                option.greeks = Algo.Model.Greeks(quote, option, Config.Local.FederalIterest, StockDividendRate, double.NaN, double.NaN);                row.ImpliedVolatility = option.greeks.implied_volatility;              row.Delta = option.greeks.delta;              row.Gamma = option.greeks.gamma;              row.Vega = option.greeks.vega;              row.Theta = option.greeks.theta;          }          catch { }            try          {              // add row to table (if new)              if (new_row) OptionsTable.Rows.Add(row);          }          catch { }            // save option in cache          if (option_cache.ContainsKey(option.symbol)) option_cache[option.symbol] = option;          else option_cache.Add(option.symbol, option);      }  

This is where I am calling updateoptionstable:

public void Update(string stock)      {          // update quote table          Quote quote = null;            try          {              // update quote data base              quote = UpdateQuotesTable(stock);          }          catch { }            if (quote != null)          {              try              {                  // update database version and creation date                  Version = Config.Local.CurrentVersion;                  DatabaseCreationDate = DateTime.Now;                  UpdateDate = DateTime.Now;                    // update options table                  UpdateOptionsTable(quote.stock, quote);                    // update conversion tables                  UpdateConversionTables();                    // update historical volatility                                if ((Config.Local.GetParameter("Volatility Mode") == "Stock HV") ||                      (Config.Local.GetParameter("Download Historical Volatility") == "Yes"))                  {                      UpdateHistoricalVolatility(quote.stock);                  }                    // update derived data                  UpdateDerivedData(quote, true, true, true, true);              }              catch { }          }      }   

and in the end the update function is used by :

private void downloadWorker_DoWork(object sender, DoWorkEventArgs e)      {          // update stock data          core.Update(stockText.Text);            // update interset rate if (auto update is enabled)          if (Config.Local.GetParameter("Federal Interest Auto Update") == "Enabled")          {              Config.Local.SetInterest("Federal", Comm.Server.GetAnnualInterestRate(1.0));          }      }  

Rest of the things is being shown in the grid but neither I am getting any error nor this data was able to populate on the screen. Can someone please review and correct me if I am doing anything wrong here.

These are the datatable and bindingsource I am using in the code:

    //Initialize Components    this.optionsTableBindingSource = new System.Windows.Forms.BindingSource(this.components);      ((System.ComponentModel.ISupportInitialize)(this.optionsDataGridView)).BeginInit();              ((System.ComponentModel.ISupportInitialize)(this.optionsTableBindingSource)).BeginInit();              this.optionSelectionGroupBox1.SuspendLayout();              this.optionSelectionGroupBox3.SuspendLayout();              this.optionSelectionGroupBox2.SuspendLayout();              this.optionSelectionGroupBox4.SuspendLayout();              this.stockGroupBox.SuspendLayout();                  this.optionsDataGridView.DataSource = this.optionsTableBindingSource;  // optionsTableBindingSource              //               this.optionsTableBindingSource.DataMember = "OptionsTable";              this.optionsTableBindingSource.DataSource = this.optionsSet;  #MainForms  ((System.ComponentModel.ISupportInitialize)(this.optionsDataGridView)).EndInit();          ((System.ComponentModel.ISupportInitialize)(this.optionsTableBindingSource)).EndInit();          this.optionSelectionGroupBox1.ResumeLayout(false);          this.optionSelectionGroupBox3.ResumeLayout(false);          this.optionSelectionGroupBox2.ResumeLayout(false);          this.optionSelectionGroupBox4.ResumeLayout(false);          this.stockGroupBox.ResumeLayout(false);          this.stockGroupBox.PerformLayout();  

and this is how updatebuttonclick event works:

private void updateButton_Click(object sender, EventArgs e)      {          // execute only once          if (downloadWorker.IsBusy) return;            // clear database if symbol is new          if (updateButton.Text == "Update") newButton_Click(sender, e);            // show download message          updateButton.Visible = false;          autoRefreshCheckBox.Visible = false;          serverProgressBar.Value = 0;          serverProgressBar.Visible = false;          progressLabel.Visible = false;          downloadLabel.Visible = true;                        // control tour progress          if (balloonForm.Active) balloonForm.Hide();            // suspend binding          optionsTableBindingSource.SuspendBinding();          optionsTableBindingSource.RaiseListChangedEvents = false;             positionsTableBindingSource.SuspendBinding();          positionsTableBindingSource.RaiseListChangedEvents = false;             resultsTableBindingSource.SuspendBinding();          resultsTableBindingSource.RaiseListChangedEvents = false;             // run worker          downloadWorker.RunWorkerAsync();      }  

Laravel 8 - Class not found error using SDK

Posted: 23 Aug 2021 08:09 AM PDT

I'm using the SDK provided online to connect the payment API, and I'm sure the SDK can work successfully. However, as I followed the steps setting up my code, I got an error. I think it might because of the different Laravel version I used.

I want to use the class "Newebpay" in my PurchasesController.php, but I got the error message: Class 'Newebpay' not found.

Here is my PurchasesController.php code:

<?php    namespace App\Http\Controllers;    use Illuminate\Foundation\Auth\Access\AuthorizesRequests;  use Illuminate\Foundation\Bus\DispatchesJobs;  use Illuminate\Foundation\Validation\ValidatesRequests;  use Illuminate\Routing\Controller as BaseController;  use Newebpay;    class PurchasesController extends Controller  {      use AuthorizesRequests, DispatchesJobs, ValidatesRequests;        public function index()      {          return view('purchases.index');      }        public function purchase()      {          $newebpay = new NewebPay();          return $newebpay->payment(              '549881412984', // 訂單編號              123, // 交易金額              'test', // 交易描述              'kk@gmail.com' // 付款人信箱          )->submit();      }  }  

I've followed the instruction in the SDK, adding 'NewebPay' => Treerful\NewebPay\NewebPay::class,in the \config\app.php 'aliases' part as the code below.

'aliases' => [            'App' => Illuminate\Support\Facades\App::class,          ...                    'NewebPay' => Treerful\NewebPay\NewebPay::class,      ],  

For more details, here is my git repository of this project.

I've updated my repository, and tried all the possible solution in the command below. I still got the error.

https://github.com/shigenogoro/newebpay_testing

Ansible Playbook Directory Structure - using /files at playbook_dir level

Posted: 23 Aug 2021 08:09 AM PDT

QUESTION; TLDR

Are there suggestions on handling FILES and VAULT FILES within a playbook and not within ROLES?

EXPLANATION

I'm familiar with the following best practices from ansible where the following directory structure is listed as such:

inventories/     production/        hosts               # inventory file for production servers        group_vars/           group1.yml       # here we assign variables to particular groups           group2.yml        host_vars/           hostname1.yml    # here we assign variables to particular systems           hostname2.yml       staging/        hosts               # inventory file for staging environment        group_vars/           group1.yml       # here we assign variables to particular groups           group2.yml        host_vars/           stagehost1.yml   # here we assign variables to particular systems           stagehost2.yml    library/  module_utils/  filter_plugins/    site.yml  webservers.yml  dbservers.yml    roles/      common/      webtier/      monitoring/      fooapp/  

This structure works for simple projects. However a very large playbook, that uses requirements.yml to git clone roles into it's structure makes it hard to maintain items like vault files because of possible drift in vault-passwords amongst the myriad repos. From my perspective, it would be useful if the vaulted files were in a central location at the playbook level.

I was wondering if there is a way to create a playbook_dir/vault | files directory, at the same level as inventories or perhaps a playbook_dir/inventories/group_vars/vault | files directory. Then within this vault | files folder I can centralize all my necessary secret/non-secret files (such as certs and other items too long winded to be stored as a variable).

That way when the playbook is ran for [servers] it will get all the necessary variables AND vaulted | files that I need the host group to share.

Binance Futures not match with python-binance

Posted: 23 Aug 2021 08:09 AM PDT

I am using python and the library "python-binance". I am trying to print the values of the 1000SHIBUSDT Perpetual and check if the values are corrects. But when I check it, the values don't match. This is my code:

import pandas as pd  from pandas_datareader import data as pdr  import numpy as np  import matplotlib.pyplot as plt    from main import * # Here it is the code with the API and that  plt.style.use('fivethirtyeight')    # PRimero calcular los candlesticks  df = pd.DataFrame(client.futures_historical_klines_generator(symbol="1000SHIBUSDT", interval="5m", start_str="2021-05-12", end_str="2021-08-02"))    # crop unnecessary columns  df = df.iloc[:, :6]  # ascribe names to columns  df.columns = ['date', 'open', 'high', 'low', 'close', 'volume']  # convert timestamp to date format and ensure ohlcv are all numeric  df['date'] = pd.to_datetime(df['date'], unit='ms')  for col in df.columns[1:]:      df[col] = pd.to_numeric(df[col])  df.head()  print(df)    #Calculate the Short/Fast Exponential Moving Average  ShortEMA = df.close.ewm(span=4, adjust=False).mean() #AKA Fast moving average  print(ShortEMA)  #Calculate the Middle Exponential Moving Average  MiddleEMA = df.close.ewm(span=9, adjust=False).mean() #AKA Slow moving average  print(MiddleEMA)  #Calculate the Long/Slow Exponential Moving Average  LongEMA = df.close.ewm(span=18, adjust=False).mean() #AKA Slow moving average  print(LongEMA)    

And this is the output:

                     date      open      high       low     close     volume  0     2021-05-12 00:00:00  0.030487  0.030914  0.030105  0.030619  146477248  1     2021-05-12 00:05:00  0.030638  0.030679  0.030105  0.030108   95847357  2     2021-05-12 00:10:00  0.030125  0.030342  0.029960  0.030031  190089999  3     2021-05-12 00:15:00  0.030046  0.030153  0.029118  0.029822  315092370  4     2021-05-12 00:20:00  0.029822  0.029854  0.029258  0.029537  156433019  ...                   ...       ...       ...       ...       ...        ...  23612 2021-08-01 23:40:00  0.006265  0.006268  0.006252  0.006253   30643868  23613 2021-08-01 23:45:00  0.006254  0.006353  0.006254  0.006310  294072401  23614 2021-08-01 23:50:00  0.006311  0.006343  0.006310  0.006332   47961454  23615 2021-08-01 23:55:00  0.006332  0.006335  0.006307  0.006307   37737032  23616 2021-08-02 00:00:00  0.006308  0.006330  0.006293  0.006323   60366420    [23617 rows x 6 columns]  0        0.030619  1        0.030415  2        0.030261  3        0.030085  4        0.029866             ...     23612    0.006265  23613    0.006283  23614    0.006303  23615    0.006304  23616    0.006312  Name: close, Length: 23617, dtype: float64  0        0.030619  1        0.030517  2        0.030420  3        0.030300  4        0.030147             ...     23612    0.006285  23613    0.006290  23614    0.006299  23615    0.006300  23616    0.006305  Name: close, Length: 23617, dtype: float64  0        0.030619  1        0.030565  2        0.030509  3        0.030437  4        0.030342             ...     23612    0.006314  23613    0.006313  23614    0.006315  23615    0.006314  23616    0.006315  Name: close, Length: 23617, dtype: float64  

So... as you can see, at 00:00 of 02 of August of 2021, the values are : 0.006308(0) 0.006330(H) 0.006293(L) 0.006323(C) .

And in Binance are: 0.006417(O) 0.006443(H) 0.006405(L) 0.006441(C).

COMPLETELY DIFFERENT Even the EMAs are differents.

Can you help me to fix it?

I want to get IP addresses of users who enter my site with Asp.net core

Posted: 23 Aug 2021 08:09 AM PDT

        var webClient = new WebClient();            var ipAddress = webClient.DownloadString("http://checkip.dyndns.org");          ipAddress = (new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")).Match(ipAddress).Value;  

// gives my site IP address

Python: subprocess.call('nvm ls', shell=True) giving this error /bin/sh: nvm: command not found

Posted: 23 Aug 2021 08:09 AM PDT

def runLinter2( ):  subprocess.call('nvm ls', shell=True)  return  

When i run this python script, it gives error "error /bin/sh: nvm: command not found" but when i tun simply this nvm ls in the terminal, it works.

To run python script, i am using this command python3 test.py

Could i get help on it?

How to fix 'The type or namespace name could not be found ' error in unity?

Posted: 23 Aug 2021 08:08 AM PDT

I am setting up a new scriptable object in Unity 5 and when I am trying to set up a reference to it an error shows up :'The type or namespace name 'ES' could not be found (are you missing a using directive or an assembly reference?'

the scriptable object script:

using System.Collections;  using System.Collections.Generic;  using UnityEngine;  [CreateAssetMenu(fileName = "new ES", menuName = "ES")]    public class LAMP: ScriptableObject {      public int groupNum;        void Start() {            groupNum = 1;        }    }  

the reference in monobehavior script:

using System.Collections;  using System.Collections.Generic;  using UnityEngine;    public class Bout: MonoBehaviour {        public ES et;        // Use this for initialization      void Start() {        }        // Update is called once per frame      void Update() {        }  }  

xp_readerrorlog "Invalid parameter type" with variable

Posted: 23 Aug 2021 08:09 AM PDT

I'm trying to write some code to query the SQL Error Log from a SQL 2008R2 instance. Here's what I have:

declare @Start_Time  DATETIME = NULL;  declare @End_Time    DATETIME = NULL;    IF @Start_Time IS NULL     SELECT @Start_Time = GETDATE()-1  IF @End_Time   IS NULL     SELECT @End_Time   = GETDATE()    select @start_time start_time, CONVERT(VARCHAR(19),@start_time,120) conv_s_time  select @End_time   end_time,   CONVERT(VARCHAR(19),@End_time,120)   conv_e_time  EXEC xp_ReadErrorLog 0, 1, '', '', '2015-09-17 11:47:16', '2015-09-18 11:47:16'   EXEC xp_ReadErrorLog 0, 1, '', '', ' + CONVERT(VARCHAR(19),@Start_Time,120) '   EXEC xp_ReadErrorLog 0, 1, '', '', ' + CONVERT(VARCHAR(19),@Start_Time,120) ' , ' + CONVERT(VARCHAR(19),@End_Time,120) '  

The output of this is:

start_time  conv_s_time  2015-09-17 11:59:10.617 2015-09-17 11:59:10    end_time    conv_e_time  2015-09-18 09:35:10.617 2015-09-18 09:35:10    LogDate ProcessInfo Text  <  2000+ rows of data >    LogDate ProcessInfo Text  <  45,000+ rows of data >    Msg 22004, Level 12, State 1, Line 0  Error executing extended stored procedure: Invalid Parameter Type  

The call to xp_ReadErrorLog works with two hardcoded dates (start and end) and with one variable as the start date but fails when both start and end dates are specified as variables. Does anyone have any suggestion on why I can't use variables for both parameters in the call to xp_ReadErrorLog?

Any help appreciated.

Ken

SQL Stored procedure and coding language

Posted: 23 Aug 2021 08:10 AM PDT

So I am working on editing an existing stored procedure on a SQL server(2008 R2). I am running into some issues though due to my entry level knowledge of SQL. The issue is that the requirements for the report this generates have changed and the value of a field has changed from 2 to 3. The field length on the report was changed by the previous user, but they never accounted for instances where the data in the field only equals 2 characters. I.E. 20 or 03 instead of 100. This is causing the report to generate the values as such: '03 XX' instead of 003XX this is a problem because the system that receives this reads it from right to left so it will see these Null values and reject the whole report.

What I want to do is change the existing SET statement to a conditional statement that adds a padding '0' when the field value is only 2 char in length.

what I have currently is this:

SET @SupplyQuan = ISNULL((SELECT Unit FROM dbo.Supplyvalue(@UserID)                                WHERE Number = 3),'')  

What I need is a statement that reads similar to the following. The term I am having trouble with is the "Charactervalue". I cannot find the SQL term for the value of a "cell" or field. I was thinking possibly "Columnvalue", but that doesn't seem to be correct. I am sure the answer is a very elementary one and I am probably overthinking this. Here is the code.

SET @SupplyQuan = ISNULL((SELECT Unit FROM dbo.Supplyvalue(@UserID)                                WHERE Number = 3),'') IF "Charactervalue=3" ELSE IF "Charactervalue=2" THEN  SET @SupplyQuan = ISNULL('0'+(SELECT Unit FROM dbo.Supplyvalue(@UserID)                                WHERE Number = 3),'')  

Javascript - Dynamically assign onclick event in the loop

Posted: 23 Aug 2021 08:09 AM PDT

I have very simple html page with js code:

<html>      <head>          <title></title>      </head>      <body>            <div id="divButtons">            </div>            <script type="text/javascript">              var arrOptions = new Array();                for (var i = 0; i < 10; i++) {                  arrOptions[i] = "option" + i;              }                for (var i = 0; i < arrOptions.length; i++) {                  var btnShow = document.createElement("input");                  btnShow.setAttribute("type", "button");                  btnShow.value = "Show Me Option";                  var optionPar = arrOptions[i];                  btnShow.onclick = function() {                      showParam(optionPar);                  }                    document.getElementById('divButtons').appendChild(btnShow);              }                function showParam(value) {                  alert(value);              }                  </script>      </body>  </html>  

That page binds 10 buttons, but when you click on any button it always shows alert "option9". How is it possible assign onclick event to show correspondent option !?

Thanks!

Joining Results from Two Separate Databases

Posted: 23 Aug 2021 08:09 AM PDT

Is it possible to JOIN rows from two separate postgres databases?

I am working with system with couple databases in one server and sometimes I really need such a feature.

No comments:

Post a Comment