Wednesday, June 2, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How can I tell whether SvelteKit's "load" function is running on the server vs. client?

Posted: 02 Jun 2021 09:19 AM PDT

I'm trying to do API calls in a SvelteKit page from the load function, but I don't want to proxy these calls with local endpoints because I want to keep the web server as light as possible.

What I want to do specifically is, when the call is made from the server, the API's URL should be different than when it's called from the client (e.g. "http://localhost:1234" vs. "https://example.com:1234", respectively).

But, more generally than this, is there a way to differentiate whether the current code is running on the server vs. the client?

Can I connect CoAPthon (CoAP of Python) to node-coap(CoAP for nodejs)?

Posted: 02 Jun 2021 09:19 AM PDT

I am working on a raspberry pi project where I run python script and I want to send the sensor data from that script to my nodejs server. I am trying to connect a CoAP server in python script to my client at the node server. The libraries used are CoAPthon in python and node-coap in nodejs. When I try to connect the CoAPServer says encoding is wrong any solution for this??? The error: "utf-8' codec can't decode byte 0xbd in position 3: invalid start byte".
The python version of server that is CoAPthon server is as below.

#CoAPServer.py  from coapthon.server.coap import CoAP  from coapthon.resources.resource import Resource  gotin=1  class sensor(Resource):      def __init__(self, name="sensor", coap_server=None):          super(sensor, self).__init__(name, coap_server, visible=True,observable=True, allow_children=True)          self.payload = str(gotin)          self.content_type = "text/plain"      def render_GET(self, request):          return self  class CoAPServer(CoAP):      def __init__(self, host, port):          CoAP.__init__(self, (host, port))          self.add_resource('/sensor', sensor())  def main():      server = CoAPServer("0.0.0.0", 5682)      try:          server.listen(10)      except KeyboardInterrupt:          print("Server Shutdown")          server.close()  if __name__ == '__main__':      main()  

The nodejs CoAP client is as below.

//app.js  const express = require("express");  const app = express();  const path = require("path");  const port = process.env.PORT || 3000;  app.use(express.static(path.join(__dirname, "public")));  var coap = require('coap');  var packet = require('coap-packet');  var req = coap.request({    host: '127.0.0.1',    pathname: '/sensor',    port: 5682,    method: 'get'  })  var payload = {    user : 'ash'  }  req.write(JSON.stringify(payload));  req.setOption('Content-Format','text/plain');  console.log(req);  req.on('response', function(res) {    console.log('response code', res.code);    res.pipe(process.stdout)  });  req.end();  app.listen(port, () => {    console.log(`🚀🚀Listening on port : ${port}`);  });  

The error am getting is

Traceback (most recent call last):    File "E:\practice\raspberrypi\CoAPServer1.py", line 28, in <module>      main()    File "E:\practice\raspberrypi\CoAPServer1.py", line 23, in main      server.listen(10)    File "C:\Users\91948\AppData\Local\Programs\Python\Python39\lib\site-packages\coapthon\server\coap.py", line 153, in listen      message = serializer.deserialize(data, client_address)    File "C:\Users\91948\AppData\Local\Programs\Python\Python39\lib\site-packages\coapthon\serializer.py", line 57, in deserialize      message.token = token_value.decode("utf-8")  UnicodeDecodeError: 'utf-8' codec can't decode byte 0x91 in position 0: invalid start byte    

Infinite loop in array MIPS

Posted: 02 Jun 2021 09:19 AM PDT

So I'm new to MIPS and I'm trying to build a program in Assembly MIPS which finds the maximum value in array:

    .data       A: .word 11 100 3 5 8 13 1 16  #array of integers      N: .word 8  # array length      output_max: .asciiz "The max value is: "            .text      .globl main        main:      la $a0 N      la $a1 A            jal max      move $s0 $v0            # jal min      # move $s1 $v0            #Stampa risultati      li $v0 4      la $a0 output_max      syscall            li $v0 1      move $a0 $s0      syscall      j exit              exit:      li $v0 10      syscall    max:            move $t0 $a0        move $t1 $a1        lw $v0 0($t1)        li $t2 0        j maxLoop        maxLoop:      addi $t2 $t2 1       beq $t2 $t0 maxEnd        addi $t1 $t1 4       lw $t3 0($t1)      slt $t4 $v0 $t3       beq $t4 1 changeMax      j maxLoop        changeMax:      move $v0 $t3      j maxLoop              maxEnd:      jr $ra  

The max function should return the maximum value in the input array. So after compiling, it goes into an infinite loop. I can't quite see where the problem is..

Spring Batch - Chunk Oriented Processing without transactions

Posted: 02 Jun 2021 09:18 AM PDT

I've been researching various batch frameworks and I appreciate the abstraction and out-of-the-box features such as skip, retry, listeners etc. that Spring Batch brings with it and I'm familiar with Spring framework so this is a natural choice.

However, the batch flows I intent to create do not have transactional databases on either end of the reader-process-write flow. I desire to use Spring Batch to connect two systems through API's and still leverage the batch framework for tracking job executions and back the batch app with the Spring Batch database.

The remote API's support their own batching concepts, so, we can be sure to process 100 records and attempt to batch insert where the entire batch fails when one record is invalid. In that way, I would still like Spring Batch to "rollback" and retry each record individually.

Is it possible to leverage Spring Batch with its backing batch metadata database, to use skip and retry, without holding database connections or using transactions during chunk based processing?

Passing WebMethod Value to .aspx Page

Posted: 02 Jun 2021 09:18 AM PDT

Project 1 : (From Where I am Sending MemberCode "10002") on Button Click

protected void lnkRFQ_Click(object sender, EventArgs e)  {      dynamic strReturn = null;      var _input = new { CLIENT_ID = txtMember.Text != null ? txtMember.Text : "", };      var result = new { input = _input };        string inputJson = (new JavaScriptSerializer()).Serialize(result);      HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8,"application/json");      HttpResponseMessage response = client.PostAsync("http://localhost:52211/test.aspx/SetSession", inputContent).Result;        if (response.IsSuccessStatusCode)      { strReturn = response.Content.ReadAsStringAsync().Result; }      else      { string result1 = ("Product" + response.Content.ReadAsStringAsync().Result); }      }  

Project 2 : (Where I am Receiving MemberCode "10002") in Web Method & Stored in Session

[WebMethod(EnableSession = true)]  public static dynamic SetSession(dynamic input)   {         var MemberCode = input["CLIENT_ID"]; Page objp = new Page();      objp.Session["strDwnPath"] = MemberCode;      string sessinp = objp.Session["strDwnPath"].ToString();      return input;  }  

My Question Is How Can I Pass This Session Or Value in JavaScript Function After i receive here...???

Pandas dataframe avoid looping through columns and rows

Posted: 02 Jun 2021 09:19 AM PDT

I have a df with several columns that looks somewhat like this:

A B C
NaN 3 2
6 4 NaN
2 4 NaN
1 NaN NaN
NaN NaN NaN
... ... ...

I want to create now a new column which is column 'A' multiplied by a scalar (df['D'] = df['A']*3 ) but only for those rows, where there is no NaN. In rows where there is a NaN value, I want to use the same row of column B instead and if there is also an NaN I want to use column C and so on. If all columns have NaN, the value is supposed to be NaN as well.

I could use a for-loop where I go through row by row and check above described if-statements, but that seems very unefficient for a big df. Is there any more efficient method to use here? Maybe using df.apply somehow?

Sorry if this question is very obvious.

How to get count with the 2 conditions inside ArrayList object Kotlin

Posted: 02 Jun 2021 09:19 AM PDT

Let say I have this model class.

data class Bike(      val bikeId: String? = null,      val type: String? = null,      val color: String? = null,  )  

If I want to get the count for color, I can use this:-

val freqs = list.groupingBy { it.color }.eachCount()  

Result will be:-

{GREEN=3, YELLOW=12}  

How to get count where type also included?

Example result like:-

{MOUNTAIN and GREEN=2}  {FOLDING and GREEN=1}    {MOUNTAIN and YELLOW=5}  {FOLDING and YELLOW=1}  {BMX and YELLOW=6}  

and so on..

Adding <div class to php results in Syntax Error

Posted: 02 Jun 2021 09:19 AM PDT

I'm trying to add div classes (or maybe I should be using span) to a group of filter/sort options. Unfortunately I can't seem to find the issue with the code and what I am trying I get the following Syntax Error:

syntax error, unexpected ''<div class="gift-latest">'' (T_CONSTANT_ENCAPSED_STRING), expecting ';' or ','  

Here is the original code:

    <?php echo '<div id="jgs-search">'.JLayoutHelper::render('default_filter', array('view' => $this), dirname(__FILE__));  echo JText::_('COM_JGIFTS_SORTBY').' '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_LATEST', 'a.id', $listDirn, $listOrder).' | '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_NAME', 'a.gift_name', $listDirn, $listOrder).' | '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_CATID', 'c.title', $listDirn, $listOrder).' | '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_PRICE', 'a.gift_price', $listDirn, $listOrder). '</div>  <div class="clear">  </div><hr />  <div class="grid">'; ?>  

Here is my modified code where I am trying to add the div class to each sort object:

    <?php echo '<div id="jgs-search">'.JLayoutHelper::render('default_filter', array('view' => $this), dirname(__FILE__));  echo JText::_('COM_JGIFTS_SORTBY').' '      '<div class="gift-latest">' .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_LATEST', 'a.id', $listDirn, $listOrder).' | ' '</div>'      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_NAME', 'a.gift_name', $listDirn, $listOrder).' | '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_CATID', 'c.title', $listDirn, $listOrder).' | '      .JHtml::_('grid.sort',  'COM_JGIFTS_GIFTS_GIFT_PRICE', 'a.gift_price', $listDirn, $listOrder). '</div>  <div class="clear">  </div><hr />  <div class="grid">'; ?>  

Thank you for any help resolving this issue.

Flutter shared preference -- Unhandled Exception: Null check operator used on a null value

Posted: 02 Jun 2021 09:18 AM PDT

shared preference plug-in (shared_preferences: ^2.0.6)

It got an instance error:

aunching lib/main.dart on iPhone 12 Pro Max in debug mode...  package:travel_app/main.dart:1  Xcode build done.                                           22.3s  Connecting to VM Service at ws://127.0.0.1:59168/kc8UwLPVK5s=/ws  flutter: start  [VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value  #0      MethodChannel.binaryMessenger  package:flutter/…/services/platform_channel.dart:142  #1      MethodChannel._invokeMethod  package:flutter/…/services/platform_channel.dart:148  #2      MethodChannel.invokeMethod  package:flutter/…/services/platform_channel.dart:331  #3      MethodChannel.invokeMapMethod  package:flutter/…/services/platform_channel.dart:358  #4      MethodChannelSharedPreferencesStore.getAll  package:shared_preferences_platform_interface/method_channel_shared_preferences.dart:44  #5      SharedPreferences._getSharedPreferencesMap  package:shared_preferences/shared_preferences.dart:180  #6      SharedPreferences.getInstance  package:shared_preferences/shared_preferences.dart:56  #7      Global.init  package:travel_app/common/Global.dart:36  #8      main  package:travel_app/main.dart:13  #9      _runMainZoned.<anonymous closure>.<anonymous closure> (d<…>      

heres the my code (main.dart):

Future<void> main() async => await Global.init().then((e) => runApp(MyApp()));  

Global.dart

static Future init() async {  print("start");  final SharedPreferences prefs = await   SharedPreferences.getInstance();  print("_prefs $prefs");  }  

The source code locator error is these:(method_channel_shared_preferences.dart)

await _kChannel.invokeMapMethod<String, Object>('getAll');  

Exception has occurred. _CastError (Null check operator used on a null value)

otherwise,The system I use is a MacOS.

NSStatusBarButton.Activate event does not fire (Xamarin.Mac - C#)

Posted: 02 Jun 2021 09:18 AM PDT

I'm trying to subscribe to the Activate event of an NSStatusBarButton object in AppDelegate's DidFinishLaunching() but the event never gets invoked.

The purpose is to get notified when the top menu bar icon of the application is clicked so its contents can get populated dynamically.

using AppKit;  using Foundation;    [Register("AppDelegate")]  public class AppDelegate : NSApplicationDelegate  {      private NSStatusItem _statusBar;        public override void DidFinishLaunching(NSNotification notification)      {          this._statusBar = NSStatusBar.SystemStatusBar.CreateStatusItem(NSStatusItemLength.Variable);          this._statusBar.Title = "MyApp";          this._statusBar.HighlightMode = true;          this._statusBar.Menu = new NSMenu("MyApp");            this._statusBar.Button.Activated += (sender, e) =>          {              System.Diagnostics.Debug.WriteLine("This one does not fire.");          };            var someItem = new NSMenuItem("Some Item");          someItem.Activated += (sender, e) =>          {              System.Diagnostics.Debug.WriteLine("This one does fire.");          };          this._statusBar.Menu.AddItem(someItem);      }  }  

Apply method in Pandas showing wrong data type

Posted: 02 Jun 2021 09:18 AM PDT

While using apply() method on the StackOverflow dataset, I got an error. I was trying to find the length of each reply in the "HOBBYIST" column. The code I used was:

result = pd. read_csv ("survey_results_public.csv")  result ["HOBBYIST"]. apply (len)  

The error I got was: TypeError: object of type 'float' has no len()

Even though the data in the "HOBBYIST" column included only "Yes" and "No" (and some Null values) which is clearly not float data type.

later I changed my code to:

result ["HOBBYIST"]. astype (str). apply (len)  

This showed the correct result but why did apply method consider values like "Yes" and "No" to be float data type?

Input 0 is incompatible with layer model_1: expected shape=(None, 244, 720, 3), found shape=(None, 720, 3)

Posted: 02 Jun 2021 09:18 AM PDT

I wanted to test my model by uploading an image but I got this error. And I think I got the error somewhere in these lines, I'm just not sure how to fix.

IMAGE_SIZE = [244,720]  inception = InceptionV3(input_shape=IMAGE_SIZE + [3], weights='imagenet',include_top=False)  

Also here's the code of uploading my test image

picture =  image.load_img('/content/DSC_0365.JPG', target_size=(244,720))  img = img_to_array(picture)  prediction = model.predict(img)  print (prediction)  

I'm still a newbie in Machine learning so my knowledge right now is not yet that deep.

Add HTML tag to strings in PHP array using str_ireplace

Posted: 02 Jun 2021 09:17 AM PDT

I want to mark (highlight) the keywords a user has input as search parameters. I've tried the following PHP code to do this. It adds the tag effectively but for some reason displays each string as "Array" rather than it's value.

$find = array("HELLO","WORLD"); // Case-insensitive  $arr = array("Hello","world","!");  print_r(str_ireplace($find,'<mark>'.$find.'</mark>',$arr));  

https://i.imgur.com/7vryXlY (demo image, not enough rep to embed)

EXC_BAD_ACCESS exception on accessing name property of EspDevice class

Posted: 02 Jun 2021 09:18 AM PDT

I'm getting EXC_BAD_ACCESS exception on accessing name property of EspDevice class. I need to access deviceName which is a private property, and name is causing this error. Can somebody help me to sort this issue out. Thanks

Bug image

Adding numbers with recursion in a pyramid form

Posted: 02 Jun 2021 09:18 AM PDT

I have this given Array {1,2,3,4,5} and I should create an output like this with recursion:

48  20 28  8 12 16  3 5 7 9  1 2 3 4 5  

I have to add the value of [i] with the value of [i+1]. In the end it should have a form of a pyramid.

This is my code:

package Übungen;    public class Symmetrie {      public static void main(String[] args) {          //0 is just a placeholder to avoid an error in line 21          int[] b = {1, 2, 3, 4, 5, 0};          int j = 5;          reku(b, j);      }        public static void reku(int[] num, int j) {          System.out.println("");          if (j > 0) {              for (int i = 0; i < j; i++) {                  System.out.print(num[i] + " ");                  num[i] = num[i] + num[i + 1];              }              reku(num, j - 1);          }      }  }  

It creates an output like this:

1 2 3 4 5  3 5 7 9  8 12 16  20 28  48  

I think I have to use the stack when I use the recursion. But I have no idea how.

Cheerio Incomplete Html

Posted: 02 Jun 2021 09:18 AM PDT

i'm trying to scrap a website using cheerio

const rp = require('request');  const cheerio = require('cheerio');      rp('https://www.fideyo.com/list',(error,response,html) =>  {      if(!error && response.statusCode == 200)      {       const $ = cheerio.load(html);                    console.log($.html());      }      });    

but it returns an incomplete html body like

<body>    <div id="app"></div>    <script type="text/javascript" src="https://cdn.fideyo.com/static/main.js?v=13"></script>    <!-- Google Tag Manager (noscript) -->  <noscript>      <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-KBGVCP3"              height="0" width="0" style="display:none;visibility:hidden">      </iframe>  </noscript>  <!-- End Google Tag Manager (noscript) -->    </body></html>    

when i load site from chrome there is content in app section

how can i reach content in app section?

Entity Framework LINQ complex query

Posted: 02 Jun 2021 09:18 AM PDT

I'm trying to create a complex Linq query that goes like this: Get all organisations which have employees that match the given filter parameters.

Example filter:

  • Firstname: John
  • Name: Smith

My first attempt:

if (!filter.Name.IsNullOrWhiteSpace())  {      query = query.Where(o => o.Persons.Any(p => p.Name.ToLower().Contains(filter.Name.ToLower())));  }    if (!filter.Firstname.IsNullOrWhiteSpace())  {      query = query.Where(o => o.Persons.Any(p => p.Firstname.ToLower().Contains(filter.Firstname.ToLower())));  }    if (!filter.ContactNumber.IsNullOrWhiteSpace())  {      query = query.Where(o => o.Persons.Any(p => p.ContactNumber.contains(filter.ContactNumber)));  }  

The problem with this approach is that when there is someone with the firstname John (ex. John Johnson) in organisation A, and someone with the last name Smith (Jenny Smith) in organisation A. The organisation (A) that contains those two persons gets returned. Which it shouldn't. I only want organisations that have people with the firstname "john" AND the lastname "Smith"

I found a working, but dirty and non-scalable approach:

if (!filter.ContactNumber.IsNullOrWhiteSpace())  {      if (!filter.Name.IsNullOrWhiteSpace() && !filter.Firstname.IsNullOrWhiteSpace())      {          query = query.Where(o => o.Persons.Any(p => p.ContactNumber.contains(filter.ContactNumber)                                                  && p.Name.ToLower().Contains(filter.Name.ToLower())                                                  && p.Firstname.ToLower().Contains(filter.Firstname.ToLower())));      }      else if (!filter.Name.IsNullOrWhiteSpace())      {          query = query.Where(o => o.Persons.Any(p => p.ContactNumber.contains(filter.ContactNumber)                                                  && p.Name.ToLower().Contains(filter.Name.ToLower())));      } else if (!filter.Firstname.IsNullOrWhiteSpace())      {          query = query.Where(o => o.Persons.Any(p => p.ContactNumber.contains(filter.ContactNumber)                                                  && p.Firstname.ToLower().Contains(filter.Firstname.ToLower())));      } else      {          query = query.Where(o => o.Persons.Any(p => p.ContactNumber.contains(filter.ContactNumber));      }  } else if(!filter.Name.IsNullOrWhiteSpace())  {      if (!filter.Firstname.IsNullOrWhiteSpace())      {          query = query.Where(o => o.Persons.Any(p => p.Firstname.ToLower().Contains(filter.Firstname.ToLower()) && p.Name.ToLower().Contains(filter.Name.ToLower())));      } else      {          query = query.Where(o => o.Persons.Any(p => p.Name.ToLower().Contains(filter.Name.ToLower())));      }  } else if (!filter.Firstname.IsNullOrWhiteSpace())  {      query = query.Where(o => o.Persons.Any(p => p.Firstname.ToLower().Contains(filter.Firstname.ToLower())));  }  

As you can see this not a very clean solution.

I also tried using method calls inside the expression but Linq couldnt translate that. Is there any way I can can make a list of predicate expressions an merge them to one? Or is there a another, better solution?

By the way, since I need a paginated list, it all has to be in one query.

For your information, this is what my filter class looks like. It is just a class send from my front-end with all the fields that need to be filtered.

public class ContactFilter  {      public string Name{ get; set; }      public string Firstname{ get; set; }      public string ContactNummer { get; set; }  }  

Is this Dynamic polymorphism or not?

Posted: 02 Jun 2021 09:18 AM PDT

The output of the program is A isn't it suppose to be B. If I change the modifier of method in Class A to public then the output is B. Can somebody explain what is going on here?

Code:

public class HelloWorld {      public static void main(String[] args) {          HelloWorld hw = new HelloWorld();          hw.createInstance();      }        public void createInstance() {          A b = new B();          b.isTrue();      }            public class A {          private void isTrue() {              System.out.println("A");          }      }      public class B extends A {          public void isTrue() {               System.out.println("B");          }      }  }  

Output: A

How to terminate SQL statements when using DEFAULT value and OleDB?

Posted: 02 Jun 2021 09:18 AM PDT

Using C# and the JET OleDB driver (Microsoft.Jet.OLEDB.4.0) to connect to an old Access database (think Access 97). The following SQL statements work fine:

ALTER TABLE [MyTable] ADD [FunkyInt] Integer DEFAULT 3  ALTER TABLE [MyTable] ADD [FunkyString] Text(30) DEFAULT hello  

But terminating the statement with a semi-colon (;) causes problems:

ALTER TABLE [MyTable] ADD [FunkyInt] Integer DEFAULT 3;  -- syntax error  ALTER TABLE [MyTable] ADD [FunkyString] Text(30) DEFAULT hello; -- default is now "hello;"  

Can SQL statements with DEFAULT be terminated?

How to convert string YYYYMM to date in hive sql

Posted: 02 Jun 2021 09:18 AM PDT

I have column as string in the format "yyyymm" in hive table, and i would like to convert this to date with day as first of each month. for example 202105 string i would like this to be as date "2021-05-01".

Appreciate your help in this matter.

Can I Transfer list items into a 'pyqt5 list' with GUI? (In a class) | Python 3 (+ Pyqt5)

Posted: 02 Jun 2021 09:18 AM PDT

I have make already the main window, but I don't have design-save my second window, because I want to know how to transfer list items into a 'pyqt5 list' (QListWidget)... I mean that I may need to add a QListWidget to my GUI, but it may also not work, and it may be worked with something else. I didn't try something, I searth about it on Youtube and on this site too. I didn't find anything. So, how can it be? (List already exists.)

Edit: I want the changes to be live.

Edit: See the comments for more-new information.

Extract first word to first space - POSTGRES

Posted: 02 Jun 2021 09:18 AM PDT

me again!

I have this query that returns this result:

select descripcion from evento where descripcion ~ 'Act. datos:Actualización';  

output => enter image description here

I would like to extract only the first word to the first space.

I used the following query:

select upper(substring(substring(descripcion,28),0,length(substring(descripcion,28))-position(' ' in reverse(substring(descripcion,28)))+1)) from evento where descripcion ~ 'Act. datos:Actualización';  

output => enter image description here

But it gives me back everything, not just the first word before the first space.

**How can I get the following result

  1. CARMEN
  2. CARMEN
  3. CARMEN
  4. ARGOS
  5. ARGOS
  6. CARMEN
  7. EMAS

etc...**

Thank you in advanced!

Is it possible to implement it by OWL ontology?

Posted: 02 Jun 2021 09:18 AM PDT

Could you please tell me, is it possible to implement such case by just OWL ontology definitions? Or I need to create custom rules for it?

IF    ?doc rdf:type :document    AND ?doc :state :completed    AND not exists { ?other-doc :replaces+ ?doc AND ?other-doc :state :completed }  THEN    ?doc rdf:type :latest-document  

So the idea is to assign inferred :latest-document type to all entities with rdf:type :document which have :state = :completed and there is no any newer entity with :state = :completed. And I am wondering, if this case is too complex to implement it just by OWL definitions or not.

Is it possible to get the middle element through the remove() method of the LinkedList class?

Posted: 02 Jun 2021 09:18 AM PDT

I was implemented the function to queue/dequeue in memory through LinkedList of JDK.

To queue memory, call the addLast() method in 'A' Thread.

To dequeue memory, call the remove() method in 'B' Thread.

I think the FIFO structure is implemented in the above two ways in 2 different threads.

The application I implemented is written as a log when dequeue.

However, a customer using my application claims that the intermediate element is logged when the remove() function is called very very very very rarely when dequeueing.

I know this is nonsense.

However, a customer constantly annoys me by asking why the intermediate element is logged when dequeueing.

Is it possible to get the middle element through the remove() method of the LinkedList class?

My sample code like this.

public class TestClass {            static SimpleDateFormat _sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");      static String beforeTime = null;            public static void main(String[] args) {            LinkedList<String> ll = new LinkedList<String>();                    Thread t1 = new Thread(new Runnable() {                            @Override              public void run() {                  // TODO Auto-generated method stub                  while (true) {                      synchronized (ll) {                          ll.addLast(getDateTime());                      }                                            try {                          Thread.sleep(100);                      } catch (Exception e) {                          // TODO: handle exception                      }                  }              }          });          t1.start();                    Thread t2 = new Thread(new Runnable() {                            @Override              public void run() {                  // TODO Auto-generated method stub                  while(true) {                                            synchronized (ll) {                                                    if (ll.size() > 0) {                                                            String nowTime = ll.remove();                              if (nowTime != null) {                                                                    // compare                                  if (beforeTime != null) {                                                                            try {                                          if (_sdf.parse(beforeTime).after(_sdf.parse(nowTime))) {                                              System.out.println("WTF");                                          }                                      } catch (Exception e) {                                          // TODO: handle exception                                      }                                     }                                    try {                                      System.out.println(String.format("[%s] : ", getDateTime()) + nowTime);                                  } catch (Exception e) {                                      // TODO: handle exception                                  }                                                                    beforeTime = nowTime;                              }                          }                      }                  }              }          });          t2.start();      }            private static String getDateTime() {          Date date = new Date(System.currentTimeMillis());            try {              String dateTime = _sdf.format(date);              return dateTime;          } catch (Exception e) {              // TODO: handle exception          }            return null;      }  }  

Implement message sender for Artemis 2.17.0 in Java 6 and GlassFish server

Posted: 02 Jun 2021 09:17 AM PDT

I'm working in an rather old system that uses Java 6 and is deployed in GlassFish 2.1 server.

In that system I need to develop a message sender to ActiveMQ Artemis 2.17.0. Is there a way to achieve this?

I have been searching for solutions but the compatibility issues are a constant problem.

regex expression working in chrome but throwing error in safari

Posted: 02 Jun 2021 09:19 AM PDT

The below expression working in chrome but throwing error in safari regex expression:

/(?<=>#tableVits)\w+(.*?#tableVite<)/g;  

Azure Terraform NSG rule creation ERROR for DestinationAddressPrefix/DestinationAddressPrefixes as "AzureMonitor"

Posted: 02 Jun 2021 09:18 AM PDT

EDITED NEW POST TO ADD MORE CLARIFICATION:

In current architecture we run ansible playbook (infrastructure.yml) to deploy infrastructure in Azure. We are ABLE TO CREATE resources with no problems including many other NSG rules.

With new NSG rule, our terraform run fails with following information below:

I have Azurerm version as:

provider "azurerm" {    version = "2.58.0"    ...  

Terraform version:

Terraform v0.13.4  

I am able to create same rule through Azure CLI command as following:

az network nsg rule create -g 'MyGroup' --nsg-name 'MyNSG' -n 'AllowAzureMonitorOutbound' --priority 1200 --source-address-prefixes "*" --destination-address-prefixes AzureMonitor --destination-port-ranges 443  --direction Outbound --access Allow --protocol Tcp --description "AzureMonitor rule CLI creation."  

But I am getting this error while creating an NSG rule through Terraform :

**-- Original Error: Code="SecurityRuleParameterContainsUnsupportedValue" Message="Security rule parameter DestinationAddressPrefix for rule with Id /subscriptions/XXXXXXXXXXXXXX/resourceGroups/MyGroup/providers/Microsoft.Network/networkSecurityGroups/UMyNSG/securityRules/AllowAzureMonitorOutbound cannot specify existing VIRTUALNETWORK, INTERNET, AZURELOADBALANCER, '*' or system tags. Unsupported value used: AzureMonitor."**     

<------------- Code and HashicoVault values--------------->

The code snip for terraform:

resource "azurerm_network_security_group" "prx" {    name                = "${var.prx_hosts.name}-NSG"    resource_group_name = azurerm_resource_group.MYPROJECT.name    location            = var.location    dynamic "security_rule" {      for_each = var.prx_hosts.security_group.rules      content {        name                         = security_rule.value.name        description                  = security_rule.value.description        access                       = security_rule.value.access        direction                    = security_rule.value.direction        protocol                     = security_rule.value.protocol        priority                     = security_rule.value.priority        source_address_prefix        = security_rule.value.source_address_prefixes == ["any"] ? "*" : null        source_address_prefixes      = security_rule.value.source_address_prefixes == ["any"] ? null : tolist(security_rule.value.source_address_prefixes)        destination_address_prefix   = security_rule.value.destination_address_prefixes == ["any"] ? "*" : null        destination_address_prefixes = security_rule.value.destination_address_prefixes == ["any"] ? null : tolist(security_rule.value.destination_address_prefixes)        source_port_range            = security_rule.value.source_port_ranges == ["any"] ? "*" : null        source_port_ranges           = security_rule.value.source_port_ranges == ["any"] ? null : tolist(security_rule.value.source_port_ranges)        destination_port_range       = security_rule.value.destination_port_ranges == ["any"] ? "*" : null        destination_port_ranges      = security_rule.value.destination_port_ranges == ["any"] ? null : tolist(security_rule.value.destination_port_ranges)      }    }  }  

The HashicoVault values we pass to terraform like:

        "security_group": {            "name": "MY_PROJECT_NAME",            "rules": [              {                "access": "allow",                "description": "AzureMonitor rule CLI creation.",                "destination_address_prefix ": "AzureMonitor",                "destination_address_prefixes": [],                "destination_port_ranges": [                  443                ],                "direction": "Outbound",                "name": "AllowAzureMonitorOutbound",                "priority": 100,                "protocol": "TCP",                "source_address_prefixes": [                  "any"                ],                "source_port_ranges": [                  "any"                ]              }            ]          }  

Add prefix to debug command in VSCode

Posted: 02 Jun 2021 09:18 AM PDT

I'm debugging a Python script. My configuration looks something like this:

{    "name": "debug script.py",    "type": "python",    "request": "launch",    "program": "/path/to/script.py",    "console": "integratedTerminal"  }  

When running the script, I need to prefix it with an executable aws-access to give myself access to certain resources on AWS (otherwise I get Permission Denied errors):

aws-access python script.py  

How can I add this prefix to the debug command?

Note this is easy to do when executing my code using the Code Runner plugin:

"code-runner.executorMap": {    "python": "aws-access $pythonPath -u $fullFileName"  }  

Calculate cumulative sum from last non-zero entry in python

Posted: 02 Jun 2021 09:18 AM PDT

I have a numeric series like [0,0,0,0,1,1,1,0,0,1,1,0]. I would like to calculate the numeric sum from the last non-zero values. i.e the cumsum will be reset to zero once a zero entry occurs.

input: [0,0,0,0,1,1,1,0,0,1,1,0]  output:[0,0,0,0,1,2,3,0,0,1,2,0]   

Is there a built-in python function able to achieve this? Or better way to calculate it without loop?

How to change the internal IP of Kubernetes worker nodes?

Posted: 02 Jun 2021 09:18 AM PDT

I am trying to deploy a K8s cluster from scratch using Kelsey Grammer's Learn Kubernetes the hardway guide. In my case I am using vagrant and VirtualBox.

Each of My Master and Workers have a dhcp network in eth0(10.0.2.x range) for pulling bits from the internet and a eth1 static range (10.10.10.x/24) for internal k8s communication.

 [vagrant@master-1 ~]$ kubectl get nodes -o wide  NAME       STATUS   ROLES    AGE   VERSION   INTERNAL-IP   EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION              CONTAINER-RUNTIME  worker-1   Ready    <none>   32s   v1.12.0   10.0.2.15     <none>        CentOS Linux 7 (Core)   3.10.0-957.1.3.el7.x86_64   containerd://1.2.0-rc.0  worker-2   Ready    <none>   2s    v1.12.0   10.0.2.15     <none>        CentOS Linux 7 (Core)   3.10.0-957.1.3.el7.x86_64   containerd://1.2.0-rc.0  

I initially did not have the flags -node-ip="10.10.10.x and -address="10.10.10.x" setup.

Upon adding - I did remove the nodes and restart the kubelet service hopefully to register the nodes again however it seems to not want to update.

== Following is a sample of the kubelet config:

/var/lib/kubelet/kubelet-config.yaml  kind: KubeletConfiguration  apiVersion: kubelet.config.k8s.io/v1beta1  authentication:    anonymous:      enabled: false    webhook:      enabled: true    x509:      clientCAFile: "/var/lib/kubernetes/ca.pem"  authorization:    mode: Webhook  clusterDomain: "cluster.local"  clusterDNS:    - "10.32.0.10"  podCIDR: "${POD_CIDR}"  resolvConf: "/run/systemd/resolve/resolv.conf"  runtimeRequestTimeout: "15m"  tlsCertFile: "/var/lib/kubelet/${HOSTNAME}.pem"  tlsPrivateKeyFile: "/var/lib/kubelet/${HOSTNAME}-key.pem"  EOF      /etc/systemd/system/kubelet.service  [Unit]  Description=Kubernetes Kubelet  Documentation=https://github.com/kubernetes/kubernetes  After=containerd.service  Requires=containerd.service    [Service]  ExecStart=/usr/local/bin/kubelet \\    --config=/var/lib/kubelet/kubelet-config.yaml \\    --container-runtime=remote \\    --container-runtime-endpoint=unix:///var/run/containerd/containerd.sock \\    --image-pull-progress-deadline=2m \\    --kubeconfig=/var/lib/kubelet/kubeconfig \\    --network-plugin=cni \\    --node-ip="$NODE_IP"    --address="$NODE_IP"    --register-node=true \\    --v=2  

and kube-api server:

[Service]  ExecStart=/usr/local/bin/kube-apiserver \\    --advertise-address=${INTERNAL_IP} \\    --allow-privileged=true \\    --apiserver-count=3 \\    --audit-log-maxage=30 \\    --audit-log-maxbackup=3 \\    --audit-log-maxsize=100 \\    --audit-log-path=/var/log/audit.log \\    --authorization-mode=Node,RBAC \\    --bind-address=0.0.0.0 \\    --client-ca-file=/var/lib/kubernetes/ca.pem \\    --enable-admission-plugins=Initializers,NamespaceLifecycle,NodeRestriction,LimitRanger,ServiceAccount,DefaultStorageClass,ResourceQuota \\    --enable-swagger-ui=true \\    --etcd-cafile=/var/lib/kubernetes/ca.pem \\    --etcd-certfile=/var/lib/kubernetes/kubernetes.pem \\    --etcd-keyfile=/var/lib/kubernetes/kubernetes-key.pem \\    --etcd-servers=https://10.10.10.11:2379,https://10.10.10.12:2379 \\    --event-ttl=1h \\    --experimental-encryption-provider-config=/var/lib/kubernetes/encryption-config.yaml \\    --kubelet-certificate-authority=/var/lib/kubernetes/ca.pem \\    --kubelet-client-certificate=/var/lib/kubernetes/kubernetes.pem \\    --kubelet-client-key=/var/lib/kubernetes/kubernetes-key.pem \\    --kubelet-https=true \\    --runtime-config=api/all \\    --service-account-key-file=/var/lib/kubernetes/service-account.pem \\    --service-cluster-ip-range=10.32.0.0/24 \\    --service-node-port-range=30000-32767 \\    --tls-cert-file=/var/lib/kubernetes/kubernetes.pem \\    --tls-private-key-file=/var/lib/kubernetes/kubernetes-key.pem \\    --v=2  

Also in vagrant I believe eth0 is the NAT device as I see the 10.0.2.15 ip assigned to all vms (master/slaves)

[vagrant@worker-1 ~]$ ip a s  1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000      link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00      inet 127.0.0.1/8 scope host lo         valid_lft forever preferred_lft forever      inet6 ::1/128 scope host         valid_lft forever preferred_lft forever  2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000      link/ether 52:54:00:75:dc:3d brd ff:ff:ff:ff:ff:ff      inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0         valid_lft 84633sec preferred_lft 84633sec      inet6 fe80::5054:ff:fe75:dc3d/64 scope link         valid_lft forever preferred_lft forever  3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000      link/ether 08:00:27:24:a4:c2 brd ff:ff:ff:ff:ff:ff      inet 192.168.0.206/24 brd 192.168.0.255 scope global noprefixroute dynamic eth1         valid_lft 3600sec preferred_lft 3600sec  4: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000      link/ether 08:00:27:76:22:4a brd ff:ff:ff:ff:ff:ff      inet 10.10.10.21/24 brd 10.10.10.255 scope global noprefixroute eth2         valid_lft forever preferred_lft forever      inet6 fe80::a00:27ff:fe76:224a/64 scope link         valid_lft forever preferred_lft forever  [vagrant@worker-1 ~]$  

I guess the ask is how to update the internal-ip and external-ip post changes to the kubelet configuration

No comments:

Post a Comment