Sunday, June 20, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Outlook desktop Addin not working with bearer token

Posted: 20 Jun 2021 07:49 AM PDT

I have developed an outlook add-in which is hosted on one domain say "https://domainId" communicates with an api on hosted on another domain "https://domain2". It gets the token from domain and uses it to fetch other data using a bearer token fetched from domain2. This all works fine on outlook web. But the issue comes when it tries to fetch the data from the api using the bearer token. It throws a Network Error for all request involving the bearer token.

I included the domain in the manifest AppDomains list but still it throws that error. Both domains are https and even cors are enabled

Need help to resolve this issue

Access Denied - Myphp Admin - Cannot connect: invalid settings

Posted: 20 Jun 2021 07:49 AM PDT

I am pretty new to python and following a Flask course online. I am trying to connect Xampp with Python Flask to save/retrieve records in Mac OS. Accidentally i deleted a user under Phpadmin. After this i am not able to open PhpAdmin. This is how it appears enter image description here

I tried to remove Xammp and install the xampp again. After this , even my MySQl is not starting.

enter image description here

DMS Task fail for EC2 oracle as source

Posted: 20 Jun 2021 07:49 AM PDT

Last failure message Last Error Endpoint initialization failed. Task error notification received from subtask 0, thread 0 [reptask/replicationtask.c:2859] [1020401] Cannot retrieve Oracle archived Redo log destination ids; Failed to set stream position on context 'now'; Error executing command; Stream component failed at subtask 0, component

Scraping vivino.com review comments return empty data

Posted: 20 Jun 2021 07:48 AM PDT

Using Python3, I want to scrape review comments from a wine page in vivino.com. For example, scrolling down this page leads you to the section called "Community reviews", that's what I want to scrape. But my code returns an empty data. In fact, looking at the content of requests.get(url), I cannot spot the reviews section. Can anybody help me figure out why and suggest me a solution?

Here is my attempt:

from bs4 import BeautifulSoup  import requests  import time    url = "https://www.vivino.com/FR/en/dauprat-pauillac/w/3823873?year=2017&price_id=24797287"    headers = headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'}  data = requests.get(url, headers = headers) # this returns data but isn't capturing the section with review comments.    soup = BeautifulSoup(data.text, 'html.parser')  soup.find_all('div', id='all_reviews')    >>>  []  

Convert date type object to datetime

Posted: 20 Jun 2021 07:48 AM PDT

I have a dataframe with Date_Birth in the following format: July 1, 1991 (as type object). How can I change the entire column to datetime?

Thanks

Paging state is not recovering until queue is empty in ActiveMQ Artemis

Posted: 20 Jun 2021 07:48 AM PDT

We are facing an issue in ActiveMQ Artemis 2.17.0. One of the queue went to paging state when it reached the max memory settings - max-size-bytes. After some time message count subside very much when consumer processed it. But it is not recovering the paging state until the queue is empty. Is it an expected behavior?

geoQuery with multiple location to find near by user

Posted: 20 Jun 2021 07:48 AM PDT

How can I use GeoQuery event listener to find multiple users of app near by me and show in recycler view using firebase database

select grandparent by className from child element using SASS

Posted: 20 Jun 2021 07:48 AM PDT

Updating a sass file of a child element("gigsForm"), I need to change background-image of the parent div element("LightBox-content")

Its look like in browser below;

enter image description here

Image does not display after migration aspnet MVC framework to aspnet core 3.1

Posted: 20 Jun 2021 07:48 AM PDT

After migrating my aspnet MVC framework project to aspnet core 3.1, the images that are in the project folders are no longer appearing in the view.
Please, what is happening?

<img src="@ViewBag.ImagePath" class="rounded img-fluid" alt="" id="Image1">  

Getting String from Website causes java.net.MalformedURLException (JAVA)

Posted: 20 Jun 2021 07:49 AM PDT

I'm using the following code to retrieve a String from a website (already using Internet permissions):

 public static String getText(String url) throws Exception {          URL website = new URL(url);          URLConnection connection = website.openConnection();          BufferedReader in = new BufferedReader(                  new InputStreamReader(                          connection.getInputStream()));            StringBuilder response = new StringBuilder();          String inputLine;            while ((inputLine = in.readLine()) != null)              response.append(inputLine);              in.close();            return response.toString();      }  

which shouldn't bring up any errors but it actually does so I run this code everytime I call that function:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();    StrictMode.setThreadPolicy(policy);  

Which gets rid of the crashes but I still can't read strings from a completely valid URL and just getting that malformedurl exception when debugging, I'm using API 23 so that's why I'm using a ghetto approach. That last piece of code supposedly ensures I don't have to perform the task asynchronously because I want to make it simple, I can't figure out if it isn't working bc of that / am I missing permissions (which I don't think so) / do I have to set up some king of useragent-cookies to access that url. thanks for the help as always, the responses I've received here have been always incredible.

Cannot assign value of type '()' to type 'String' trying to assign function completion to let

Posted: 20 Jun 2021 07:49 AM PDT

View:

struct ProductDetail: View {      @ObservedObject private var viewModel = ProductsModel()        @State private var Mat1Outcome: String        init(product: Product_){        **Omitted unrelated variables relating to product**              self.Mat1Outcome = self.viewModel.findProductOutcomes(material: material[currentComp1Mat], completion: {outcome in let Mat1Outcome = outcome})  **ERROR IS CAUSED BY THIS LINE**          }      var body: some View {        //This is the main stack that contains everything      VStack(alignment: .leading){      HStack{          TextField("Enter Text", text: $code)          .onAppear(){self.viewModel.findProductOutcomes(material: material[currentComp1Mat], completion: {outcome in print(outcome)})}      }    }  }  

Function:

func findProductOutcomes(material: String, completion: @escaping (String) -> Void){      let council_name = "Staffordshire"    // Completes an SQL query on the Products database to find a product by it's barcode number.  let outcomeProductURL = URL(string: "http://recyclingmadesimple.xyz/outcome.php")!  var urlRequest = URLRequest(url: outcomeProductURL)  urlRequest.httpMethod = "POST"    let postString = "council_name=\(council_name)&material=\(material)"  urlRequest.httpBody = postString.data(using: String.Encoding.utf8)    let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in      guard let data = data, error == nil else {          print(error?.localizedDescription ?? "No data")          return      }      let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])      if let responseJSON = responseJSON as? [String: Any] {          print(responseJSON)          let outcome = responseJSON["outcome"] as! Int                    completion("\(outcome)")                }  }    task.resume()    }  

Error: Cannot assign value of type '()' to type 'String'

I have managed to get the output to be sent from the function to the view using a print statement inside an onAppear() attached to a random textfield but I can't get the outcome attached to a variable. I don't really understand what type '()' means.

I tried both let Mat1Outcome = outcome and let self.Mat1Outcome = outcome as I found that in another SO for a similar problem, but both gave the same error.

Many thanks.

django static files are not being found and loaded

Posted: 20 Jun 2021 07:49 AM PDT

Using django v2.2.1

I have a given project dir. structure:

enter image description here

In root project dir. there are some static files in static dir.

In base.html file,

{% load static %}  <!doctype html>  <html lang="en">    <head>      <!-- Required meta tags -->      <meta charset="utf-8">      <meta name="viewport" content="width=device-width, initial-scale=1">        <!-- favicon -->       <link rel="shortcut icon" href="{% static 'favicon.ico' %}" />            <!-- Dropzone js -->      <link rel="stylesheet" href="{% static 'dropzone.css' %}">      <script src="{% static 'dropzone.js' %}" defer></script>        <!-- Custom js & css -->      <link rel="stylesheet" href="{% static 'style.css' %}">      .      .     

This is settings.py file:

# Static files (CSS, JavaScript, Images)  # https://docs.djangoproject.com/en/2.2/howto/static-files/    STATIC_URL = '/static/'  STATICFILES_DIR = [      os.path.join(BASE_DIR, 'static'),      os.path.join(BASE_DIR, 'sales', 'static'),  ]    MEDIA_URL = '/media/'  MEDIA_ROOT = os.path.join(BASE_DIR, 'media')  

In urls.py

from django.contrib import admin  from django.urls import include, path  from django.conf import settings  from django.conf.urls.static import static    urlpatterns = [      path('admin/', admin.site.urls),       path('', include('sales.urls', namespace='sales')),         path('reports/', include('reports.urls', namespace='reports'))     ]     urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  

Also urlpatterns for sales

urlpatterns = [      path('', home_view, name='home'),      path('sales/', SaleListView.as_view(), name='list'),      path('sales/<pk>/', SaleDetailView.as_view(), name='detail'),  ]  

But I've been getting this error

enter image description here

I have restarted the server many times.

Selecting particular months over a range of years pandas

Posted: 20 Jun 2021 07:49 AM PDT

I have imported a time series that I resampled to monthly time steps, however I would like to select all the years with only March, April, and May months (months 3,4, and 5).

Unfortunately this is not exactly reproducible data since it's a particular text file, but is there a way to just isolate all months 3, 4, and 5 of this time series?

# loading textfile    mjo = np.loadtxt('.../omi.1x.txt')    # setting up dates  dates = pd.date_range('1979-01', periods=mjo.shape[0], freq='D')    #resampling one of the columns to monthly data  MJO_amp = Series(mjo[:,6], index=dates)     MJO_amp_month = MJO_amp.resample("M").mean()[:-27] #match to precipitation time series (ends feb 2019)    MJO_amp_month_normed = (MJO_amp_month - MJO_amp_month.mean())/MJO_amp_month.std()    MJO_amp_month_normed    1979-01-31    0.032398  1979-02-28   -0.718921  1979-03-31    0.999467  1979-04-30   -0.790618  1979-05-31    1.113730                  ...     2018-10-31    0.198834  2018-11-30    0.221942  2018-12-31    1.804934  2019-01-31    1.359485  2019-02-28    1.076308  Freq: M, Length: 482, dtype: float64      print(MJO_amp_month_normed['2018-10'])    2018-10-31    0.198834  Freq: M, dtype: float64  

I was thinking something along the lines of this:

def is_amj(month):      return (month >= 4) & (month <= 6)    seasonal_data = MJO_amp_month_normed.sel(time=is_amj(MJO_amp_month_normed))  

but I think my issue is the textfile isn't exactly in pandas format and doesn't have column titles...

Confusion in understanding Boolean logic

Posted: 20 Jun 2021 07:49 AM PDT

I am trying to follow a tutorial on boolean logic given here: https://www.geeksforgeeks.org/literals-in-python/

There is an example which I cannot follow and would appreciate help.

Example:

a = (1 == True)  b = (1 == False)  c = True + 3  d = False + 7  print("a is", a)  print("b is", b)  print("c is ",c)  

Confusion: Why is b assigned 1 as False? Why is 1 again being re-used to denote False? Shouldn't 0 be the value corresponding to False? If I change the line to b = (0 == False) then print("b is", b) displays b is True How come?

pandas delete row unless strings from two columns in another dataframe

Posted: 20 Jun 2021 07:49 AM PDT

I have a big dataframe like this:

ref     leftstr           rightstr  12      fish 10           47 red A45  49      abc bread x10     green 12  116     19 cheese 19A     blue blue 4040  118     8 fish 9fish      A10 red B11  200     cheese 000        99 green 98  240     142Z cheese B     blue 42 12  450     bread 94.16       0.6 red blue  ...  

And a large list like this:

li = [      '47 red A45 bread fish 10',      'cheese 000 [purple] orangeA 99 green 98',      'bread 94.16 green 12',      '0.6 red blue abc bread x10',      'bread 19 cheese 19A 100 blue blue 4040',      '8 fish 9fish 0.6 red blue',      'bread fish 10 red A45'       ...       ]  

I want to delete rows from the df if the exact strings in leftstr and rightstr are not both present in any item (but it has to be the same item) of the list. It doesn't matter whether leftstr or rightstr appear first in the list item, or if there is text in the list item as well as leftstr and rightstr.

Desired output:  ref     leftstr           rightstr  12      fish 10           47 red A45  116     19 cheese 19A     blue blue 4040  200     cheese 000        99 green 98  

So, for example, ref 49 is deleted because, although leftstr and rightstr are both in a list item, they are not in the same list item.

Nextjs v.10 getstaticprops "revalidate" stop working on docker container

Posted: 20 Jun 2021 07:49 AM PDT

first of all i am not an expert with docker deployment.

The problem i have is that the revalidate feature suddenly stopped working and only work again only if i restart the docker container. For ex. The stock on one of the product did not change.

The webapp built using nextjs v.10 it is e-com webapp and the data came from other webapp which is wordpress that primarily served as data only.

In short, nextjs as frontend deployed on docker container on vultr vps AND wordpress as backend. Revalidate feature work for around 1 month and i need to reproduce or restart the docker container to make revalidate feature work again.

I am not really sure if this problem relate to nextjs or vultr or docker. Could someone suggest a solution or anything? I am really appreciate it if someone can help me with this. Thanks.

Discord.py Reaction statement not working

Posted: 20 Jun 2021 07:48 AM PDT

I'm trying to make a bot. It's an archive bot. If some message getting some emoji and some amount, it's moving message to specific channel that the user chooses.

But I have a problem: if reaction is ✅ and reaction user is bot, it has to not send to message to the channel. I'm trying to do here a check statement. If bot see these, It have to not work on this message because It means he moved message before.

Here is my code:

    @Bot.event      async def on_raw_reaction_add(payload):        user = Bot.get_user(payload.user_id)        guild = Bot.get_guild(payload.guild_id)        channel = guild.get_channel(payload.channel_id)        message = await channel.fetch_message(payload.message_id)        veriler()             if payload.emoji.name in veriler.emoji_list:          sıra = veriler.emoji_list.index(payload.emoji.name)          for reaction in message.reactions:            if reaction.emoji == payload.emoji.name:                    emojiCount = reaction.count              if emojiCount == veriler.adet[sıra]:                               if payload.channel_id != veriler.from_list[sıra]:                  return                if message.author.id == Bot.user.id and payload.emoji.name =="✅": #here my way to fix it                  return                if payload.message_id in veriler.msg_list:                  return                else:                  await guild.get_channel(veriler.to_list[sıra]).send("Written by {} :\n\n {}".format(message.author.mention,message.content),files=[await f.to_file() for f in message.attachments])                  await guild.get_channel(veriler.from_list[sıra]).send("{} your message moved to this channel --> {}".format(message.author.mention,Bot.get_channel(veriler.to_list[sıra]).mention))                  await message.add_reaction("✅")                  file5=open("msg_list.txt","a")                  msg_id =payload.message_id                  msg_id=str(msg_id)                  file5.write(msg_id + "\n")                  file5.close()  

When I do this, Bot is sending message again. It has to not do this because I added statements. How can I fix this problem?

How to change the annimation speed of html format by plotly?

Posted: 20 Jun 2021 07:49 AM PDT

I used px to make an annimation. We can change the speed in the jupyter notebook. But the speed does NOT change while saving as html file. How to change the following code so that the speed of html changed as well?

import plotly.express as px   df = px.data.gapminder()   fig=px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",              size="pop", color="continent", hover_name="country",              log_x=True, size_max=55, range_x=[100,100000], range_y=[25,90])  fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 50000  fig.write_html('fig.html')  

Difference between switch function and React(jsx,tsx) switch operator

Posted: 20 Jun 2021 07:49 AM PDT

We are currently porting our portfolio from Javascript to TypeScript using NextJS as frontend framework and Strapi as backend.

To have dynamic content we created a dynamiczone field inside of the post model and we get it from GraphQL.

Our problem comes when we want to render the content based on the dynamic zone type, its model is:

export interface IExperience {    id: string;    from: Date;    to?: Date;    ongoing?: boolean;    title: string;    institution: string;    address?: IAddress;    url?: string;    description?: string;  }    export interface IPersonalInformation {    id: string;    name: string;    photo: IFile;    position: string;    nationality?: string;    address?: IAddress;    telephone?: ITelephone[];    mail: string;    links?: ISocialLink[];    aboutMe?: string;  }    export interface IRichText {    id: string;    text: string;  }    export type IComponent =    | ({        __component: "content.rich-text";        __typename: "ComponentContentRichText";      } & IRichText)    | ({        __component: "content.experience";        __typename: "ComponentContentExperience";      } & IExperience)    | ({        __component: "content.personal-information";        __typename: "ComponentContentPersonalInformation";      } & IPersonalInformation)    | ({        __component: "fields.skill";        __typename: "ComponentFieldsSkill";      } & ISkill);  

The component field will extends one interface based in its type; cool, but when we go to render it we get problems:

const DynamicZone: React.FC<IDynamicZone> = ({ component, className }) => {    const classes = useStyles();      const selectComponent = () => {      switch (component.__typename) {        case "ComponentContentRichText":          return <Content>{component.text}</Content>;        case "ComponentContentExperience":          return <Experience {...component} />;        case "ComponentContentPersonalInformation":          return <PersonalInformation {...component} />;        case "ComponentFieldsSkill":          return <Skill {...component} />;      }    };      return (      <Typography        variant="body1"        component="section"        className={clsx(classes.dynamicZone, className)}      >        {          {            "content.rich-text": <Content>{component.text}</Content>, <-- Bug 1            "content.experience": <Experience {...component} />,            "content.personal-information": (              <PersonalInformation {...component} /> <-- Bug 2            ),            "fields.skill": <Skill {...component} />,          }[component.__component]        }      </Typography>    );  };    export default DynamicZone;  

With, bug 1:

<html>TS2339: Property 'text' does not exist on type 'IComponent'.<br/>Property 'text' does not exist on type '{ __component: &quot;content.experience&quot;; __typename: &quot;ComponentContentExperience&quot;; } &amp; IExperience'.  

And bug 2:

<html>TS2322: Type '{ __component: &quot;content.rich-text&quot;; __typename: &quot;ComponentContentRichText&quot;; id: string; text: string; } | { __component: &quot;content.experience&quot;; __typename: &quot;ComponentContentExperience&quot;; ... 8 more ...; description?: string | undefined; } | { ...; } | { ...; }' is not assignable to type 'IntrinsicAttributes &amp; IPersonalInformation &amp; { children?: ReactNode; }'.<br/>Type '{ __component: &quot;content.rich-text&quot;; __typename: &quot;ComponentContentRichText&quot;; id: string; text: string; }' is missing the following properties from type 'IPersonalInformation': name, photo, position, mail  

Why is it assing the type improperly?

Ok, if we change it to selectComponent function, it does not give any error:

const DynamicZone: React.FC<IDynamicZone> = ({ component, className }) => {    const classes = useStyles();      const selectComponent = () => {      switch (component.__typename) {        case "ComponentContentRichText":          return <Content>{component.text}</Content>;        case "ComponentContentExperience":          return <Experience {...component} />;        case "ComponentContentPersonalInformation":          return <PersonalInformation {...component} />;        case "ComponentFieldsSkill":          return <Skill {...component} />;      }    };      return (      <Typography        variant="body1"        component="section"        className={clsx(classes.dynamicZone, className)}      >        {selectComponent()}      </Typography>    );  };  

Esentially, it is the same thing, so, why it does not give typing errors with switch case but it does with {{}[]}?

Thanks.

Imitate command line execution from within code

Posted: 20 Jun 2021 07:48 AM PDT

I have a python project that is intended to be executed by running the head routine from the command line, i.e.:

python ssd.py --train  

However, since this is a machine learning model and I don't have a GPU, I want to run the project entirely within Google Colab. This means I can't start files using the command line (or at least I don't know how). The workaround I've chosen is to use a single notebook as the header routine.

MWE-sketch (edited):

launcher.ipynb

!cp drive/MyDrive/.../ssd.py  from ssd import SSD  SSD("train")  

ssd.py

...    __init__():     # here is code that will     # result in an error unless     # the code below is executed first    ...    # the code below is not inside any function  if __name__ == '__main__':      # here is code that      # must be executed first   

If I type python ssd.py --train into the command line, the code in ssd.py proper is executed first. If I use launcher.ipnyb, the code in __init__() is executed first, resulting in error.

How to Share Mutex, Condition Variable and Queue between two Classes C++?

Posted: 20 Jun 2021 07:49 AM PDT

When trying to learn threads most examples suggests that I should put std::mutex, std::condition_variable and std::queue global when sharing data between two different threads and it works perfectly fine for simple scenario. However, in real case scenario and bigger applications this may soon get complicated as I may soon lose track of the global variables and since I am using C++ this does not seem to be an appropriate option (may be I am wrong)

My question is if I have a producer/consumer problem and I want to put both in separate classes, since they will be sharing data I would need to pass them the same mutex and queue now how do I share these two variables between them without defining it to be global and what is the best practice for creating threads?

Here is a working example of my basic code using global variables.

#include <iostream>  #include <thread>  #include <mutex>  #include <queue>  #include <condition_variable>    std::queue<int> buffer;  std::mutex mtx;  std::condition_variable cond;       const int MAX_BUFFER_SIZE = 50;    class Producer  {      public:          void run(int val)           {                while(true) {                  std::unique_lock locker(mtx)        ;                  cond.wait(locker, []() {                  return buffer.size() < MAX_BUFFER_SIZE;                  });                    buffer.push(val);                  std::cout << "Produced " << val << std::endl;                  val --;                  locker.unlock();              // std::this_thread::sleep_for(std::chrono::seconds(2));                  cond.notify_one();              }             }  };    class Consumer   {      public:          void run()          {              while(true) {                  std::unique_lock locker(mtx);                  cond.wait(locker, []() {                  return buffer.size() > 0;                  });                    int val = buffer.front();                  buffer.pop();                  std::cout << "Consumed " << val << std::endl;                    locker.unlock();                  std::this_thread::sleep_for(std::chrono::seconds(1));                  cond.notify_one();              }          }  };      int main()  {      std::thread t1(&Producer::run, Producer(), MAX_BUFFER_SIZE);      std::thread t2(&Consumer::run, Consumer());                t1.join();      t2.join();        return 0;  }  

What is the difference between a clang (objective-C) module and a Swift module?

Posted: 20 Jun 2021 07:48 AM PDT

Clang modules are documented here, and Swift modules are here which doesn't go into as much detail.

Since clang is the LLVM frontend compiler which is also used by Swift internally, is a Swift module always a Clang module? Are they exactly the same thing?

Division operater in Neo4j

Posted: 20 Jun 2021 07:48 AM PDT

When I execute the following cypher:

CREATE (n:Person {name: 'Andy',sal:600/3, title: 'Developer'})  

The salary value will equals 300. But when execute the following:

CREATE (n:Person {name: 'Andy',sal:1/2, title: 'Developer'})  

The salary value will equals 0. What should I do to retrieve the correct answer?

Modifying value of object pointed by a shared pointer

Posted: 20 Jun 2021 07:49 AM PDT

I have recently started working with shared pointers and need some help. I have a vector 1 of shared pointers to some objects. I need to construct another vector 2 of shared pointers to the same objects, so that modifying vector 2 would result in modification of vector 2. This is how my code looks like: This works fine

class A  {      public:      int a;      A (int x) {        a = x;      }      int print() {          return a;      }  };    int main()  {      shared_ptr<A> ab = make_shared<A>(100);      cout<< ab->print();            shared_ptr<vector<shared_ptr<A>>> vec1 = make_shared<vector<shared_ptr<A>>>(1);      shared_ptr<vector<shared_ptr<A>*>> vec2 = make_shared<vector<shared_ptr<A>*>>();      vec2->push_back(&(*vec1)[0]);      for (shared_ptr<A>* obj : *vec2) {          *obj = make_shared<A>(100);      }      cout << (*((*vec1)[0])).a;   // Prints 100      return 0;  }  

But this gives a SEGV at the last line since vec1 is not populated:

class A  {      public:      int a;      A (int x) {        a = x;      }      int print() {          return a;      }  };    int main()  {         shared_ptr<vector<shared_ptr<A>>> vec1 = make_shared<vector<shared_ptr<A>>>(1);      shared_ptr<vector<shared_ptr<A>>> vec2 = make_shared<vector<shared_ptr<A>>>();      vec2->push_back((*vec1)[0]);      for (shared_ptr<A> obj : *vec2) {          obj = make_shared<A>(100);      }      cout << (*((*vec1)[0])).a;   // SIGSEGV      return 0;  }  

I want to understand why vec1 was not populated in the 2nd one and also would like to know if there is any other way of doing this. Thanks!

How to change text in the component base on the project I runs?

Posted: 20 Jun 2021 07:48 AM PDT

I build auth lib in my nx monorepo.

The auth lib contains LoginComponent (smart) and LoginFormComponent (dumb).

And I load the lib as lazy by using loadChildren to load auth.module and inside this module I have a child route to the LoginComponent which have LoginFormComponent.

Inside the LoginFormComponent I have text: "Login to my awesome app".

<h1>Login to my awesome app</h1>  <form...>  

The problem is when I want to add another angular application and use this auth components and functionality.

So when I use the auth from the new application, I'm getting the text: "Login to my awesome app".

For the existing app the text should be: "Login to my awesome app".

And for new app should be: "Login to ng app".

I have only one auth lib with one of login component.

So I looking for angular way to deal with such senario.

I was think about duplicate the component but it's not feel right. or to use i18n but not sure because it's for langs, or using forRoot and pass the providers with the text? using tokens with inject?

What the ways I can do to change the text? How to handle this issue? is it solution to angular for this senario?

How to repeat Mono while not empty

Posted: 20 Jun 2021 07:48 AM PDT

I have a method which returns like this!

Mono<Integer> getNumberFromSomewhere();  

I need to keep calling this until it has no more items to emit. That is I need to make this as Flux<Integer>.

One option is to add repeat. the point is - I want to stop when the above method emits the first empty signal.

Is there any way to do this? I am looking for a clean way.

Create jpg/png from encrypted image

Posted: 20 Jun 2021 07:49 AM PDT

I'd like to be able to convert/display an AES256 asymmetric encrypted image even if it appears to be garbage, I've read a number of things on SO that suggest removing the headers and then reattaching them afterward so even if looks nutty it still displays it.

The point of this is that I want to see if it's possible to perform image classification on an image dataset encrypted with a known public key. If I have a picture of a cat and I encrypt it with exactly the same key, then the result will generally be reproducible and result in an image that in some way equates to the original.

Excuse the lack of code, I didn't want to pollute the discussion with ideas that I was considering in order to get a proper critique from you lovely people- I would say I'm not an encryption expert hence my asking for advice here.

Shared element transition to a fragment that contains a ViewPager

Posted: 20 Jun 2021 07:48 AM PDT

I am trying to perform a shared element transition from a RecyclerView item in Fragment A to Fragment B. The transition-names are set on the outermost CardViews in both layouts. My implementation is basically the same as the one in this sample.

Everything worked fine until I added a ViewPager2 in Fragment B.

I tried to follow the steps in this answer, but to no luck.

Stack trace:

java.lang.IndexOutOfBoundsException: Index: 5, Size: 5          at java.util.ArrayList.get(ArrayList.java:437)          at androidx.fragment.app.FragmentTransitionImpl.setNameOverridesReordered(FragmentTransitionImpl.java:182)          at androidx.fragment.app.DefaultSpecialEffectsController.startTransitions(DefaultSpecialEffectsController.java:665)          at androidx.fragment.app.DefaultSpecialEffectsController.executeOperations(DefaultSpecialEffectsController.java:114)          at androidx.fragment.app.SpecialEffectsController.executePendingOperations(SpecialEffectsController.java:294)          at androidx.fragment.app.Fragment$3.run(Fragment.java:2776)          at android.os.Handler.handleCallback(Handler.java:938)          at android.os.Handler.dispatchMessage(Handler.java:99)          at android.os.Looper.loop(Looper.java:223)          at android.app.ActivityThread.main(ActivityThread.java:7656)          at java.lang.reflect.Method.invoke(Native Method)          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)  

Edit: Setting the transition name on each of the ViewPager children removed the crash, but now the transition is wrong. To be clear, Fragment B contains a CardView, which in turn has a ViewPager inside it. The added code:

    binding.viewPager.children.forEach {          it.transitionName = getString(R.string.home_item_transition_name_end)      }       

How calculate a double integral accurately using python

Posted: 20 Jun 2021 07:49 AM PDT

I'm trying to calculate a double integral given by :

import numpy as np  import scipy.special as sc  from numpy.lib.scimath import sqrt as csqrt  from scipy.integrate import dblquad      def g_re(alpha, beta, k, a, b, d, m, n, s, t):      psi = csqrt((alpha / d) ** 2 + (beta / b) ** 2 - k ** 2)      return np.real(          sc.jv(m, alpha)          * sc.jv(n, beta)          * sc.jv(s, alpha)          * np.sin(beta)          * sc.jv(t, -1j * psi * a)          * np.exp(-psi * a)          / (alpha ** 2 * psi)      )      def g_im(alpha, beta, k, a, b, d, m, n, s, t):      psi = csqrt((alpha / d) ** 2 + (beta / b) ** 2 - k ** 2)      return np.imag(          sc.jv(m, alpha)          * sc.jv(n, beta)          * sc.jv(s, alpha)          * np.sin(beta)          * sc.jv(t, -1j * psi * a)          * np.exp(-psi * a)          / (alpha ** 2 * psi)      )      k = 5  a = 0.5  b = 0.5  d = 0.1    m = 0  n = 0  s = 0  t = 0  tuple_args = (k, a, b, d, m, n, s, t)  ans = dblquad(g_re, 0.0, np.inf, 0, np.inf, args=tuple_args)[0]  ans += 1j * dblquad(g_im, 0.0, np.inf, 0, np.inf, args=tuple_args)[0]  

The integration intervals are along the positive real axes ([0, np.inf[). When calculating I got the following warning :

/tmp/a.py:10: RuntimeWarning: invalid value encountered in multiply    sc.jv(m, alpha)  g/home/nschloe/.local/lib/python3.9/site-packages/scipy/integrate/quadpack.py:879: IntegrationWarning: The maximum number of subdivisions (50) has been achieved.    If increasing the limit yields no improvement it is advised to analyze    the integrand in order to determine the difficulties.  If the position of a    local difficulty can be determined (singularity, discontinuity) one will    probably gain from splitting up the interval and calling the integrator    on the subranges.  Perhaps a special-purpose integrator should be used.    quad_r = quad(f, low, high, args=args, full_output=self.full_output,  

I subdivided the domain of integration but I still got the same warning. Could you help me please.

unknown exchange type 'x-delay-message' RabbitMq with MassTransit

Posted: 20 Jun 2021 07:48 AM PDT

I've been installed 'RabbitMQ Delayed Message Plugin'. and can be see on plugins list of RabbitMq. enter image description here

and configured MassTnasit with RabbitMq Using the follow code:

var services = new ServiceCollection();            services.AddMassTransit(x =>          {              x.AddRabbitMqMessageScheduler();                x.UsingRabbitMq((context, cfg) =>               {                  cfg.UseDelayedExchangeMessageScheduler();                    cfg.ConfigureEndpoints(context);              });          });  

and injected 'IMessageScheduler' interface to my business service and called 'IMessageScheduler.ScheduledPublish<>()'.
but I got this error: unknown exchange type 'x-delay-message' RabbitMq with MassTransit

No comments:

Post a Comment