โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayRecent Questions - Stack Overflow

RestSharp Response Content Always Null But Still Logs With Execute

When sending a basic GET the response.Content is always NULL on return. The weird thing is that it will log the content on the standard execute, but not on the async. I'm at my wit's end. Any help would be appreciated.

I tried using the standard client.Execute and client.ExecuteAsync and both seem to have the same result, except for the logging part.

The regular method (with identifying info X'd out):

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXX");

                Serilog.Log.Information($"Request is {request}");

                IRestResponse response = myClient.Execute(request);
                var htmlString = response.Content;
                Serilog.Log.Information($"Request is {response.Content}");

                return htmlString;

The executeAsync method:

                RestClient myClient = new RestClient(uri);
                var request = new RestRequest(Method.GET);

                request.AddHeader("cache-control", "no-cache");
                request.AddHeader("Connection", "keep-alive");
                request.AddHeader("accept-encoding", "gzip, deflate");
                request.AddHeader("Host", "XXXXX");
                request.AddHeader("Cache-Control", "no-cache");
                request.AddHeader("Accept", "*/*");
                request.AddHeader("Authorization", "XXXXXXXXXX");

                Serilog.Log.Information($"Request is {request}");
                var htmlString = "";
                myClient.ExecuteAsync(request, response =>
                {
                    htmlString = response.Content;
                    Serilog.Log.Information($"Response is {response.Content}");
                });
                return htmlString;

Obviously I want it to both log AND return the actual content. Ok, gurus, what am I doing wrong?

unnest string array in druid in ingestion phase for better rollup

I am trying to define a druid ingestion spec for the following case. I have a field of type string array and I want it to be unnested and rolled up by druid during the ingestion. For example, if I have the following two entries in the raw data:

["a","b","c"]
["a", "c"]

In the rollup table I would like to see three entries:

"a"  2
"b"  1
"c"  2

If I just define this column as a dimension, the array is kept as is and the individual values are not extracted. I've looked on possible solution with transformSpec and Expressions, by no help. I know how to use GROUP BY in query time to get what I need, but I'd like to have this functionality during the ingestion time. Is there some way to define in in the dataSchema?

Thank you.

Open a popup (e.g. native browser) from a Teams desktop client app tab

Is there any way to pop open a browser window from a Teams app tab (desktop client)?

I came across the following link and from my interpretation of the reply it seems it's not possible.

Quoted from link for reference:

Unfortunately itโ€™s not possible to use window.open in Teams tabs. Because we block opening of new windows to arbitrary sites within our Teams Desktop Client (for security reasons) you need to always use microsoftTeams.authentication.authenticate (if you want a popup window) or microsoftTeams.tasks.startTask (if you want an iframe-based dialog) to open a secondary app view.

It's not very clear to me what the microsoftTeams.authentication.authenticate reference above is suggesting.

Alternatively, if not a browser window, can we attempt to open another app installed on the device (e.g. Excel)?

Thanks in advance!

How to force System.Text.Json serializer throw exception when property is missing?

Json.NET behaviour could be defined by attributes: either use default or just throw an exception if json payload does not contain required property.

Yet System.Text.Json serializer silently does nothing.
Having class:

public sealed class Foo
{
    [Required]
    public int Prop {get;set;} = 10;
}

and deserializing empty object:

JsonSerializer.Deserialize<Foo>("{}");

I simply get an instance of Foo with Prop=10. I could not find any setting in JsonSerializerOptions to force it throw an exception. Is it possible?

Get the Exact Entry Price in Pine Script

How to get the exact entry price for the order. In TradingView Strategy Tester I see order prices are different than one captured by the strategy which leads to a wrong calculation of the stop-loss and take-profit.

if (longCondition)
    strategy.entry("MACrossLE", strategy.long, comment="LE")
    
    entryPos                                := nz(pos[1]) == 0 and longCondition

    entry_price                             := entryPos ? open : entry_price
    
    tp_level_long                           := entry_price * (1 + tpl/100)
    sl_level_long                           := entry_price * (1 - sll/100)
    
    tp_exit                                 := nz(pos[1]) == 1 and (ta.crossover(low, tp_level_long))
    sl_exit                                 := nz(pos[1]) == 1 and (ta.crossunder(high, sl_level_long))
    
    if(tp_exit)
        strategy.exit("TP-L", from_entry="EL", qty=pos, profit = tp_level_long, stop = sl_level_long)
        strategy.close("Close_L", when=tp_exit)
        
    if(sl_exit)
        strategy.cancel("Cancel_L", when=sl_exit)

    
if (shortCondition)
    strategy.entry("MACrossSE", strategy.short, comment="SE")
    
    entryPos                                := nz(pos[1]) == 0 and shortCondition

    entry_price                             := entryPos ? open : entry_price
    
    tp_level_short                          := entry_price * (1 - tps/100)
    sl_level_short                          := entry_price * (1 + sls/100)

    tp_exit                                 := nz(pos[1]) == 1 and (ta.crossover(low, tp_level_short))
    sl_exit                                 := nz(pos[1]) == 1 and (ta.crossunder(high, sl_level_short))
    
    if(tp_exit)
        strategy.exit("TP-L", from_entry="EL", qty=pos, profit = tp_level_short, stop = sl_level_short)
        strategy.close("Close_L", when=tp_exit)
    
    if(sl_exit)
        strategy.cancel("Cancel_L", when=sl_exit)

When the LongCondition is met a strategy entry is open however I'm not getting the exact price, for example, I see in the Strategy Test 29340 while in the label of entry_price I see 29335 that's a slight difference that might affect the strategy testing.

Not I'm not using strategy.position to apply the same condition in the indicator if that's possible

Adding an interceptor to a GRPC call in Angular

I have a GRPC call being performed from an npm package which I can see from the back is using @ngx-grpc. Now I want to intercept the GRPC to perform an extra operation(I want to add a header,but it does not matter what I do) while GRPC call is being performed. I have created class for that as follows:

import { Injectable } from '@angular/core';
import { GrpcEvent, GrpcMessage, GrpcRequest } from '@ngx-grpc/common';
import { GrpcHandler, GrpcInterceptor,  } from '@ngx-grpc/core';
import { Observable } from 'rxjs';

@Injectable()
export class GrpcInterceptorHandler implements GrpcInterceptor {

  intercept<Q extends GrpcMessage, S extends GrpcMessage>(request: GrpcRequest<Q, S>, next: GrpcHandler): Observable<GrpcEvent<S>> {
    // Modify the request metadata here
    request.requestMetadata.set('custom-header', 'value');

    // Log the request and metadata for debugging purposes
    console.log('gRPC request:', request);
    console.log('gRPC metadata:', request.requestMetadata);

    // Forward the request to the next handler in the chain
    return next.handle(request);
  }
}

and added that in the providers of the app.module.ts:

{
      provide: GRPC_INSTANT_GRPC_CLIENT_SETTINGS,
      useClass: GrpcInterceptorHandler,
      multi: true,
      useValue: {
        host: environment.gatewayUrl,
        path: ""
      } as GrpcWebClientSettings,
    },

But I cannot see the interceptor being called. What I am missing in here?

How do I modify the stack list of sys.exc_info()?

I'd like to remove a couple of frames from the stack list that represent a decorator before logging it, but when I try to get to it, the debugger says that there is no such attribute as stack even though PyCharm shows it:

sys.exc_info()[2].tb_frame.stack  # <-- AttributeError, but why?

enter image description here

This is what I would like to do:

sys.exc_info()[2].tb_frame.stack = sys.exc_info()[2].tb_frame.stack[3:]

Entity Framework Core 6, select with interchangable Where clause

I'm converting some inline SQL code over to Entity Framework Core 6. The overall application is in C#. Some of the existing code has SQL that can take an optional WHERE clause.

A simplified example might look like this:

public List<DataObject> SelectWithWhere(string optionalWhere)
{    
    string sql = string.Format("SELECT * FROM SomeTable {0} ;", optionalWhere);
   
    // call to DB class to execute query and format into List (pseudo code)
    List<DataObject> list = ExecuteSqlAndFormat(sql);
 
    return list;
}

I'd like to be able to pass in Where criteria to a similar function that uses Entity Framework Core 6, but have not been able to find any good clear examples of passing a where clause, or some kind of entity structure that represents a where clause, into a method that can be then passed to EF Core.

public List<DataObject> SelectWithWhere(string optionalWhere)
{                
    List<DataObject> list = (from t in dbContext.SomeTable.Where(-- what to do here? --)
                             select new DataObject
                             {
                                  // fill in data members from query
                             }
                             ).ToList<DataObject>()
     
    return list;
}

The preferred solution would use only what is available in Entity Framework Core 6 and not any third party add-ons or proprietary tools.

Thanks!

How do I make my HTML text color an animated gradient with CSS? [duplicate]

I've got a CSS gradient and an h1 element. I want to set the text color to the gradient but it just makes it the background. I've tried an inherit but that doesn't seem to do anything.

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.gradient {
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  height: 100vh;
}
<h1 style="text-align: center; font-size: 40px;">Welcome To <span class="gradient"><b>Mnazz Suite</b></span></h1>

Is there a libcurl curl_easy_setopt() version of curl --data-urlencode

I'm tying to connect to the latest Royal Mail API V4 to get a token Based on existing working code in C and libcurl to connect to V3. I have a working curl example script which gets a token using --data-urlencode which returns a token.

curl -k --location 'https://authentication.proshipping.net/connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=AAAAAAA' \
--data-urlencode 'client_secret=BBBBBBBBB' \
--data-urlencode 'grant_type=client_credentials'

I tried the following in C and libcurl

curl_easy_setopt(hnd, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_easy_setopt(hnd, CURLOPT_URL, "https://authentication.proshipping.net/connect/token");
curl_easy_setopt(hnd, CURLOPT_POST, TRUE);

headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

postfields = curl_slist_append(postfields, "client_id=AAAAAAA");
postfields = curl_slist_append(postfields, "client_secret=BBBBBBBBB");
postfields = curl_slist_append(postfields, "grant_type=client_credentials");
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, postfields);

curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, writefunc);
curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &s);

res = curl_easy_perform(hnd);

But the libcurl sample returns the output

{"error":"invalid_client"}

Can anyone help with --data-urlencode or equivalent command in libcurl? Thanks

Count the number of instances of a string of text in an entire dataframe

I have a dataframe and I want to count the number of instances of a particular string of text.

For example in the below dataframe:

library(tidyverse)

df <- iris %>%
  select(Species) %>%
  distinct() %>%
  mutate(Species2 = Species) %>%
  mutate(Species3 = Species)

I want to count the number of times "setosa" occurs

Using length(grep("setosa", df$Species)) I can get the counts of setosa in a specific column but how can I do this to the whole dataframe?

I tried length(grep("setosa", df)) which comes back as zero

Any suggestions?

How to initialize an array of struct in C++ while specifying index

I am a little new to C++ and learning the language. Right now I'm using C++17 and GCC. I have the following struct named Spec in my C++ code.

struct Spec
{
    int val;
    double otherVal;
};

And I have an array named specData of these structs. I know in advance (at compile time) the values of the structs in my array. Thus, I can initialize my array as follows:

Spec specData[] = { 
        { .val = 1, .otherVal = 3.56 }, 
        { .val = 3, .otherVal = 9.88 },
    } ;

However, the index of each entry is important. I want to explicitly map each element in the array with some index which I will be giving an int-alias so it is clear to which subject each Spec belongs. In my code, I can then easily access the specData using the int-alias also. (My intent is that this helps to ease maintenance and to make it less error prone).

Suppose I have an Spec for each of these entries (this could be my int-alias for example):

enum class Items
{
    ITEM_NAME1   = 0,
    ANOTHER_ITEM = 1,
};

Then, I want to initialize my array something like this:

Spec specData[] = { 
        [Items::ITEM_NAME1]   = { .val = 1, .otherVal = 3.56 }, 
        [Items::ANOTHER_ITEM] = { .val = 3, .otherVal = 9.88 },
    } ;

This obviously does not compile.

I know it seems like I might better use: std::map<Items, Spec>. Altough that would probably work, however, map has an O(log N) complexity, while an array look-up is O(1) complexity. I will be looking up lots of values, so I would like to have the extra speed.

Is it possible to initialize my array like the way I want? If not, what is the second best alternative?

How to align text at bottom of <input> element

Is there a way to get the text in an <input> to NOT be vertically aligned in the center of an <input>?

I am working on a form that has an <input> element inside of an <iframe>. The title and border around the input are added to make it look like the rest of the inputs, but the credit card input is fundamentally different than the rest of the inputs on the page. I have been asked to make it so this element doesn't look off when autofill is used in the browser like this:

enter image description here

This is happening because the browser or an extension is changing the teh background color of just the <input/> element.

I have managed to get it to look like this, but as you can see, the text is not aligned in the area it should be:

enter image description here

This is the CSS I am passing to the service that handles the iframe that contains the <input> in question.

        width: calc(100% - 12px);
        border-style: none;
        padding: 0;
        font-weight: ${iframeFontWeight};
        font-size: 1rem;
        font-family: ${iframeFontFamily};
        background: ${iframeBackground};
        color: ${iframeColor};
        height: 48px;
        padding-left: 12px;
        border-radius: ${iframeBorderRadius};

I have tried adding padding to the top of the <input> which adds a vertical scroll and when the element is customized with a pill-shaped input (a requirement in this case), the border radius is not working as expected: enter image description here

I have tried line-height (no effect) and position: absolute (same problem as padding-top).

Simple reproduction of this issue: https://codesandbox.io/s/youthful-snow-ygjgwx?file=/src/index.js

Exception setting "TreatControlCAsInput": "The handle is invalid. in Windows PowerShell ISE

We have a PowerShell script that contains "[Console]::TreatControlCAsInput = $true". The script is executed in a Azure DevOps Pipeline and fails with

Exception setting "TreatControlCAsInput": "The handle is invalid.
"
At line:1 char:3
+   [Console]::TreatControlCAsInput = $true
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : ExceptionWhenSetting

We've narrowed down the issue by reproducing this with a single line of code outside of an Azure Pipeline. Simply open Windows PowerShell ISE and run this:

[Console]::TreatControlCAsInput = $true

If we do this in a Windows PowerShell command window, the line of code succeeds.

Does anyone know what is different about the two environments that causes this difference in behavior? We are hoping that the answer would help us understand and resolve the larger issue with the script that runs in an Azure Pipeline.

The script runs fine if executed:

  1. In Cmd.exe window using Powershell.exe -File ....
  2. In Windows PowerShell window

The script fails if executed in WIndows PowerShell ISE

โŒ
โŒ