Friday, February 18, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to compile GUI who uses Simulink model?

Posted: 18 Feb 2022 07:49 AM PST

I have a GUI in where I introduce parameters for evalute in Simulink model, now I want to compile this application to .exe, GUI call a script who call model and returns some operations with data provide by simulation. Is there some way to build that app? I will be very grateful for the help.

When using gradient descent to train a linear classifier, why don't we use accuracy as a loss function?

Posted: 18 Feb 2022 07:49 AM PST

I know that accuracy is not derivable. But I am confused about which one of the following is the answer?

  1. It makes the loss zero almost everywhere.

  2. The confidence interval is high on small test sets.

  3. It is only reliable in situations with high class imbalance.

  4. It causes the loss landscape to be flat almost everywhere

Generating a random graph with a given # of edges and nodes

Posted: 18 Feb 2022 07:49 AM PST

Ok this is probably a stupid question but I am not very experienced with Java. I want to generate a random graph for a given number of nodes + edges. When I run it, it returns an edgelist of all zeroes (e.g. if I run it with five nodes and edges, it returns five pairs of zeroes as the edgelist). Is there something wrong with this part of the code that would be causing that?

public GraphEdgeList(int nNodes, int nEdges){          if (nNodes != 0){              for (int i = 0; i < nEdges; i++){                  int u = (int) Math.random()* nNodes;                  int v = (int) Math.random()* nNodes;                                    addEdge(u, v);              }          }      }  

JavaFX switch between scenes from a StackPane

Posted: 18 Feb 2022 07:48 AM PST

I have to create an application and I am using JavaFX. I created a stage with a menu and multiple scenes which are called when I press buttons from menu. But now I have a problem: I do some actions in a scene and I want to move to another scene pressing a button from that scene (I do not have access to StackPane object): This is how I switch scenes from the menu:

public void homeAction(ActionEvent actionEvent) throws IOException{          Parent fxml = FXMLLoader.load(getClass().getResource("/EmployeePages/HomePane.fxml"));          employeeStackPane.getChildren().removeAll();          employeeStackPane.getChildren().setAll(fxml);          titleLabel.setText("Home");      }        public void createProjectAction(ActionEvent actionEvent) throws IOException{          Parent fxml = FXMLLoader.load(getClass().getResource("/EmployeePages/CreateProjectPane.fxml"));          employeeStackPane.getChildren().removeAll();          employeeStackPane.getChildren().setAll(fxml);          titleLabel.setText("Create new Project");      }  

Here is a screenshot with the interface, maybe this is clear: enter image description here

All i want is to be able to switch to another scene when i press that button.

Is it possible to make sticky label for text which can be overflowed in flutter?

Posted: 18 Feb 2022 07:48 AM PST

It's easy to understand what I want to do by looking at the following screenshots.

When there isn't too much text, I want the label to snuggle up to it. enter image description here

When the text doesn't fit completely on one line, I want it to overflow like in the screenshot. enter image description here

Has anyone encountered a similar problem and knows how to do it in the proper way?

Is it possible to program a for loop in any programming language?

Posted: 18 Feb 2022 07:48 AM PST

Note: This is for a teaching exercise in Python

Python based pseudocode:

  def for_loop(int > index, int > range) {    if index==range{  stop  }  else{  #code  index=index+1  }  }  

Dynamically selecting the column to select from the row itself in SQL

Posted: 18 Feb 2022 07:48 AM PST

I have a SQL Server 2018 table with some data as follows

Id SelectedP P1 P2 P3 P4 P5
1 P2 3 8 4 15 7
2 P1 0 2 6 0 3
3 P3 1 15 2 1 11
4 P4 3 4 6 2 4

I need to write a SQL statement which can get the below result. Basically which column that needs to be selected from each row depends upon the SelectedP value in that row itself. The SelectedP contains the column to select for each row.

Id SelectedP Selected-P-Value
1 P2 8
2 P1 0
3 P3 2
4 P4 2

Thanks in advance.

Error in karate-config.js when the callsingle feature file scenrio fails

Posted: 18 Feb 2022 07:49 AM PST

I am calling an API in karate-config.js to generate the token. Sometime this API fails and returns a 504 error as we have performance issue.

I am using callsingle to call this feature file and then storing the token to be used in all other feature files. This is how I am calling this token API in karate-config.js

var token = karate.callSingle('classpath:common/token.feature');  config.token = token.response.tokenValue;  

Whenever any API fails karate-config.js prints the whole file on console with below error.

  1. Can I abort test if above callSingle fails?
  2. How to use try and catch block here?
  3. It prints the whole karate-config.js file on console whenever this callSingle operation fails how to avoid this.
  4. Below is the error that comes at the end once it print the whole karate-config.js on console. I am not able to understand this exception please guide.
<<<<  org.graalvm.polyglot.PolyglotException: status code was: 504, expected: 200, response time in milliseconds: 59986, url: https://myurl/token, response:   ***  classpath:common/token.feature:22  - com.intuit.karate.core.ScenarioBridge.callSingle(ScenarioBridge.java:234)  - com.intuit.karate.core.ScenarioBridge.callSingle(ScenarioBridge.java:179)  - <js>.fn(Unnamed:64)    - com.intuit.karate.graal.JsEngine.fromJsEvalException(JsEngine.java:230)  - com.intuit.karate.core.ScenarioEngine.executeJsValue(ScenarioEngine.java:1244)  - com.intuit.karate.core.ScenarioEngine.executeFunction(ScenarioEngine.java:1227)  - com.intuit.karate.core.ScenarioEngine.getOrEvalAsMap(ScenarioEngine.java:1216)  - com.intuit.karate.core.ScenarioRuntime.evalConfigJs(ScenarioRuntime.java:291)  - com.intuit.karate.core.ScenarioRuntime.beforeRun(ScenarioRuntime.java:369)  - com.intuit.karate.core.ScenarioRuntime.run(ScenarioRuntime.java:395)  

How to optimise React Native App Performance in terms of preventing component re-rendering again and again

Posted: 18 Feb 2022 07:48 AM PST

I would like to improve component performance but after analysis of many components I got to know there is a very huge amount of re-rendering is going on with each component, is there any way to reduce the re-rendering of components in React?

java-red envelopes -chinese algorithm [closed]

Posted: 18 Feb 2022 07:49 AM PST

I'm new to java and trying to find solution to this problem

Goal:
In Chinese culture, it is common during celebrations to give "red envelopes" containing a little money. Most often, the adult generations give to the younger generations. You want to build a wechat application to help grandparents share their donation budget between their grandchildren.

Write a program that calculates the number of "lucky gifts" (equal to 8) according to the money budget and the number of giftees grandchildren

Functioning:

Many rules, mixing tradition and superstition, frame this gift:

Donations should not contain amount 4, as it sounds like "dead" it is favorable to donate an amount of 8, as it sounds like "fortune" it would be disapproved not to give anything to one of the grandchildren your algorithm must return the number of donations equal to 8 while respecting the following rules:

Spend the entire budget (unless there is enough budget to give everyone 8)
Give no 4 (by tradition, the budget will never be 4)
Give no 0 (unless the budget is not sufficient)
Score a maximum of 8 once the above rules are respected
implementation:

implement the function luckyMoney(money,giftees) which :

take as inputs the integers money and giftees with:

0 <=money< 100

0 <=giftees<10

and returns the number of donations equal to 8 as an integer

Examples:

inputs: 12,2 output:0  inputs: 24,4 output:2  inputs: 7,2 output:0  

My solution:

public class ChineseGift {        public static int luckyMoney(int money, int giftees){          String strMoney=String.valueOf(money);          if(strMoney.contains("8") || money == 0) {              return -1;          }          if (money % 8 == 0){              return (money / 8);          } else if (money % 4 == 0) {              return 0;          }          return 0;      }        public static void main(String[] args) {          System.out.println(luckyMoney(12, 2));          System.out.println(luckyMoney(24, 4));// got 3 (expcted value 2) !!!      }  }  

How to ensure the setNames() attributes the correct names to my group_split() datasets when splitting by multiple groups?

Posted: 18 Feb 2022 07:49 AM PST

As a follow up to this question, I'm using dplyr's group_split() to make dataframes / tibbles based on a levels of a column. Continuing off of this question, I want to split off of two columns instead of 1. When I try to split and name the columns, it attributes the wrong names to some of the datasets.

Here's a simple example:

library(dplyr)  #Sample dataset to intuitively illustrate issue  example <- tibble(number = c(1:6),                    even_or_odd = c("odd", "even", "odd", "even", "odd", "even"),                    prime_or_not = c("prime", "prime", "prime", "not", "prime", "not")) %>%    mutate(type = paste0(even_or_odd, "_", prime_or_not)) %>%    mutate(type_factor = factor(type, levels = unique(type)))    #Does group split to make 3 datasets  the_test <- example %>%    group_split(even_or_odd, prime_or_not) %>%    setNames(unique(example$type_factor))    #The data sets with some being correct but others not  even_prime <- the_test["even_prime"]$even_prime #works!  even_not <- the_test["even_not"]$even_not #wrong label :`-(  odd_prime <- the_test["odd_prime"]$odd_prime #wrong label :`-(  odd_not <- the_test["odd_not"]$odd_not #works--correctly throws an error!    

My question: how do I ensure that my group names will be attributed to the right dataset and avoid the issues here with even_not and odd_prime being mixed up?

In my actual dataset, I have 50+ combinations, so typing them all out manually is not an option. In addition, my actual dataset will have some combinations that don't consistently exist (like the (like the odd not prime combination here), so relying on index isn't an option.

Python Pandas Increment Counter Column

Posted: 18 Feb 2022 07:49 AM PST

I have a dataframe and I intend to add a counter column. It should start with a value x and for every new row it should increase incrementally by the same value y. I already tried to apply this code:

initial_value = x      df["Counter"] = range(initial_value, len(df) + initial_value)   

But I am not sure how to continue. Does anyone have an idea?

Thank you!

PhpSpreadsheet download from post JSON data request

Posted: 18 Feb 2022 07:49 AM PST

I don't see any exceptions client or server side but the file never downloads. I'm assuming the client isn't handling the response correctly ...

client code:

var f = 'exportFile';  var params = ...    $.post('../../functions/export_functions.php', {f: f, params: params}, function(data) {        if (data.success) {          //        }      else if (data.error) {          displayError(data.error);      }      else {          displayError('An error occurred while exporting file.');      }    }, "json");  

server code:

public function exportFile($params=null) {            try {            $writer = new Xlsx($spreadsheet);                        ...            // set headers          header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');          header('Content-Disposition: attachment;filename="'.$export_file_name.'"');          header('Cache-Control: max-age=0');                        return $writer->save('php://output');      }      catch (Exception $e) {          //      }  }  

Any thoughts?

Thanks, -Paul

Postman - Cannot deserialize instance of `java.util.ArrayList<example>` out of START_OBJECT token

Posted: 18 Feb 2022 07:49 AM PST

I am using postman and I am getting the deserialize error with my json code:

 {      "vrfName": "PostmanVRF",      "lanAttachList": [        {          "fabric": "{{fabric-name}}",          "vrfName": "PostmanVRF",          "serialNumber": "90T9HZYS027",          "vlan": 2001,          "deployment": false,          "extensionValues": "",          "instanceValues": "",          "freeformConfig": "",          "msoCreated": false,          "msoSetVlan": false        }      ]  }  

I saw other topics related to this error but never in postman and don't know what to do.

Thank you,

How can I average across sheets defined by an INDIRECT value?

Posted: 18 Feb 2022 07:48 AM PST

I have 4 sheets in this sample, each with a value in A1, as follows:

  • Sheet1 - A1=18
  • Sheet2 - A1=15
  • Sheet3 - A1=197
  • Sheet4 - A1=534

Then in Sheet5 I have:

  • B1='Sheet1
  • B2='Sheet4

I want an average of A1 cells from Sheet1 to Sheet4, and I can accomplish this easily with the formula =AVERAGE(Sheet1:Sheet4!A1) in Sheet5!A1.

My problem is I want to do that same formula but referencing the sheet values in B1 and B2. I think I need INDIRECT for this, so I tried =AVERAGE(INDIRECT(B1 & ":" & B2 & "!A1")). When I enter that, though, I get a #REF! error. What could Excel be failing to reference?

How can i check my word for a specific letter from a user input?

Posted: 18 Feb 2022 07:49 AM PST

I'm creating a hangman game how can I check my word for a specific letter from a user input? I know there isn't much code here but I'm stuck and cant quite find any answers to my problem

//word or phrase in variable  {   string word = "supercalifragilisticexpialidocious"   //blanked out word / phrase   string blanked = "___________________________________"   // #of incorrect guesses    int guesses = 6   // letter guesses   string letter_guess = input("enter a letter guess: ")      //start loop   while()   {     }   //if guess incorrect do this   // how do i check the var for correct letters     //elif guess correct do this     //elif out of guesses do this     //else do this  }  

How do I subtract a tuple from floats in a function? Gives error: TypeError: unsupported operand type(s) for -: 'tuple' and 'float'

Posted: 18 Feb 2022 07:49 AM PST

I have a quick question. I want to get three answers when I return the Power function since I have three numbers in my tuple t2. But it gives me this error I can't do anything with. Pls help.

t1 = 25.0  t2 = 228.66, 235.6763, 248.161  speed = 100.16  width = 943.0   thickness = 0.26    def Power(t2, t1):      "Test123"      Power = (t2-t1)*speed*width*thickness*6*10**-5      return Power    print(Power(t2, t1))  

Can we schedule a Worksheet on Snowflake?

Posted: 18 Feb 2022 07:48 AM PST

I have recently started to use snowflake and trying to get my hands on this tool. I am trying to copy a table from my Snowflake to an Azure storage Blob using the copy into statement creating an external stage. I was wondering if there is a way to schedule a worksheet like every in 5 min or a particular time of the day daily? And if there is a way to trigger this worksheet only when there is a change in the table?

Thanks in advance

Using back camera on mobile web to scan a document

Posted: 18 Feb 2022 07:49 AM PST

So I'm using cypress to automate integration tests for both mobile and mobile web.

One of the tests that I'm doing currently involves users using the back-facing camera to scan documents which are scanned via a third party API.

The issue I'm having is that this third party API doesn't detect the camera (it's important to note that the webcam is detected with no issues) so my question is:

Is there any way with Cypress to enable / mock the back facing camera in any way?

I've found flags to enable/disable webcam, but found nothing for back facing camera.

Thanks a lot in advanced!

Android studio Pictures disappear?

Posted: 18 Feb 2022 07:48 AM PST

In android studio When I put a picture in the program and exit the program and return to the program the picture disappears, what fixes this thing?

How do you edit the command line in an external editor?

Posted: 18 Feb 2022 07:49 AM PST

tl;dr

I want to find a Powershell version of the bash edit-and-execute-command widget or the zsh edit-command-line widget.

Background

Short commands get executed directly on the command-line, long complicated commands get executed from scripts. However, before they become "long", it helps to be able to test medium length commands on the command-line. To assist in this effort, editing the command in an external editor becomes very helpful. AFAIK Powershell does not support this natively as e.g. bash and zsh do.

My current attempt

I am new to Powershell, so I'm bound to make many mistakes, but I have come up with a working solution using the features of the [Microsoft.Powershell.PSConsoleReadLine] class. I am able to copy the current command-line to a file, edit the file, and then re-inject the edited version back into the command-line:

Set-PSReadLineKeyHandler -Chord "Alt+e" -ScriptBlock {    $CurrentInput = $null      # Copy current command-line input, save it to a file and clear it    [Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref] $CurrentInput, [ref] $null)    Set-Content -Path "C:\Temp\ps_${PID}.txt" -Value "$CurrentInput"    [Microsoft.PowerShell.PSConsoleReadLine]::KillRegion()      # Edit the command with gvim    Start-Job -Name EditCMD -ScriptBlock { gvim "C:\Temp\ps_${Using:PID}.txt" }    Wait-Job  -Name EditCMD      # Get command back from file the temporary file and insert it into the command-line    $NewInput  = (Get-Content -Path "C:\Temp\ps_${PID}.txt") -join "`n"    [Microsoft.PowerShell.PSConsoleReadLine]::Insert($NewInput)  }  

Questions

My current solution feels clunky and a somewhat fragile. Are there other solutions? Can the current solution be improved?

Environment

  • OS Windows 10.0.19043.0
  • Powershell version 5.1.19041.1320
  • PSReadLine version 2.0.0

When I delete an item from the RecycleView, I delete the data from the Firebase Database, but the RecylerView is not updated. What should I do?

Posted: 18 Feb 2022 07:48 AM PST

In my fragment named FragmentFavs, I get the data from Firebase and show it in the RecyclerView.

This is my model data class

data class NewsDBModel(      val key : String? ="",      val author : String? = "",      var title : String? = "",      val description : String? = "",      val url : String? = "",      val urlToImage : String? = "",      val publishedAt : String? = ""    )  

This is my FragmentFavs

class FragmentFavs : Fragment() {      private lateinit var bind : FragmentFavsBinding      private lateinit var arrNews : ArrayList<NewsDBModel>      private lateinit var ref : DatabaseReference      private lateinit var auth: FirebaseAuth        override fun onCreateView(          inflater: LayoutInflater,          container: ViewGroup?,          savedInstanceState: Bundle?      ): View? {          bind = FragmentFavsBinding.inflate(inflater, container, false)          return bind.root      }        override fun onCreate(savedInstanceState: Bundle?) {          super.onCreate(savedInstanceState)          setHasOptionsMenu(true)        }        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {          super.onViewCreated(view, savedInstanceState)            bind.rvFavs.setHasFixedSize(true)          bind.rvFavs.layoutManager = LinearLayoutManager(context)            arrNews = arrayListOf<NewsDBModel>()          getFavorites()        }        private fun getFavorites() {          auth = Firebase.auth          val currentUser = auth.currentUser          if(currentUser!=null){              val uid = currentUser.uid              ref = FirebaseDatabase.getInstance().getReference("favorites").child(uid)                  ref.addValueEventListener(object : ValueEventListener{                  override fun onDataChange(snapshot: DataSnapshot) {                        if(snapshot.exists()){                          for(favSnapshot in snapshot.children){                              val news = favSnapshot.getValue(NewsDBModel::class.java)                              arrNews.add(news!!)                          }                          bind.rvFavs.adapter = FavoritesAdapter(context!!,arrNews)                        }                  }                    override fun onCancelled(error: DatabaseError) {                    }                })            }else{              val intent = Intent(context,Login::class.java)              startActivity(intent)            }        }    }  

Then when I want to delete the item in the cardview, I successfully delete it from the database, but the RecyclerView is not updated.

Also, when I delete an item, that item is deleted, but other items are copied and displayed. I can't understand why.

When the deletion is done, I delete the item from the arraylist and run the notifyItemRemoved() method, but it doesn't work. What should I do?

This is my RecyclerView adapter

class FavoritesAdapter(val context : Context, var arrNews : ArrayList<NewsDBModel>): RecyclerView.Adapter<FavoritesAdapter.ModelViewHolder>() {      val database = Firebase.database      private lateinit var auth: FirebaseAuth      val myRef = database.getReference("favorites")        class ModelViewHolder(val bind: FavoritesRowBinding): RecyclerView.ViewHolder(bind.root){}        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ModelViewHolder {          val bind = FavoritesRowBinding.inflate(LayoutInflater.from(parent.context),parent,false)          return ModelViewHolder(bind)      }        override fun onBindViewHolder(holder: ModelViewHolder, position: Int) {            holder.bind.txtFavoritesDate.text = arrNews.get(position).publishedAt.toString().trim()          holder.bind.txtFavoritesAuthor.text = arrNews.get(position).author.toString().trim()          holder.bind.txtFavoritesTitle.text = arrNews.get(position).title.toString().trim()                       holder.bind.cardViewFav.setOnClickListener {                auth = Firebase.auth              val currentUser = auth.currentUser              val uid = currentUser!!.uid              myRef.child(uid).child(arrNews.get(position).key!!).removeValue()              arrNews.removeAt(position)              notifyItemRemoved(position)                         }      }        override fun getItemCount(): Int {          return arrNews.size      }  }  

Flutter Signalr Listener is not connected in 2nd screen after migrated to null safety stable version

Posted: 18 Feb 2022 07:48 AM PST

Chatting was working perfectly before migrating to null safety using signalr. But after migrating It is not working in chatting part.

Scenario is like there are 2 screens where I am using signalr. 1)Chatlist. 2)Chatting with person.

listener in Chatlist is perfect but in 2nd screen it is not working(Just worked when I installed and run for the 1st time). Weird issue.

All was working in old. I am using bloc for statemanagement and also migrated to yield to emit.

Piece of code is like:

 void listenOnMessageReceived(        HubConnection hubConnection,        Function(Message? chatMessageReceive) onMessageReceived,        ) {      final SocketResponseCallBack chatMessageReceived =          (response) => onMessageReceived(Message.fromJson(response));      final hubMethod = HubMethod(          CHAT_RECEIVED_MESSAGE_METHOD_NAME,          SignalRHelper.toSocketFunction(              CHAT_RECEIVED_MESSAGE_METHOD_NAME, chatMessageReceived));        bool exists = listenOnHubMethod.any((method) => method.methodName == CHAT_RECEIVED_MESSAGE_METHOD_NAME);      if(exists) {        listenOnHubMethod.removeWhere((element) =>        element.methodName == CHAT_RECEIVED_MESSAGE_METHOD_NAME);        SignalRHelper(hubConnection: hubConnection).on(          hubMethod.methodName,          hubMethod.methodFunction,        );        listenOnHubMethod.add(hubMethod);      }else{        SignalRHelper(hubConnection: hubConnection).on(          hubMethod.methodName,          hubMethod.methodFunction,        );        listenOnHubMethod.add(hubMethod);      }    }  

I am having 2 types of above code in different screens. but it is working in only 1 screen and not listening in 2nd screen.

here is a piece of signalr listener code:

  static MethodInvocationFunc toSocketFunction(        String methodName, SocketResponseCallBack responseCallBack) {      return (arguments) {        try {          if (arguments!.isEmpty) {            throw SocketEmptyResponseException(methodName);          }          final response = arguments.first;          responseCallBack(response);        } on FormatException {          throw SocketResponseException(methodName);        }      };    }    

Is there any limitations in migration of stable version or anything else. Every help is appreciable. Thank you.

Conditional Statements for terraform modules

Posted: 18 Feb 2022 07:48 AM PST

We have two projects lets say A & B and three modules X,Y,Z (modules/X,Y,Z) for these two projects separately and do changes regularly & changes will be deployed to those A & B projects. Every time for a change we need to add in both project modules respective folders and its hard for us to track those changes.

Project A -> (modules/X,Y,Z)

Project B -> (modules/X,Y,Z)

We have decided to move identical modules to common folder and for different modules need to write conditional statements to work for respective projects.

Project A -> (modules/Z)

Project B -> (modules/Z)

(common/X,Y)

X & Y modules we have moved to common folder as both are identical and works for both projects whereas Z module has different changes which will not work in this case. Is there any option to write conditional statements to pick specific lines of code to get deployed for A & B projects.

Most efficient paradigm for checking if a key exists in a c++ std::unordered_map?

Posted: 18 Feb 2022 07:49 AM PST

I am relatively new to modern c++ and working with a foreign code base. There is a function that takes a std::unordered_map and checks to see if a key is present in the map. The code is roughly as follows

uint32_t getId(std::unordered_map<uint32_t, uint32_t> &myMap, uint32_t id)   {     if(myMap.contains(id))     {       return myMap.at(id);     }     else     {       std::cerr << "\n\n\nOut of Range error for map: "<< id << "\t not found" << std::flush;       exit(74);     }  }  

It seems like calling contains() followed by at() is inefficient since it requires a double lookup. So, my question is, what is the most efficient way to accomplish this? I also have a followup question: assuming the map is fairly large (~60k elements) and this method gets called frequently how problematic is the above approach?

After some searching, it seems like the following paradigms are more efficient than the above, but I am not sure which would be best.

  • Calling myMap.at() inside of a try-catch construct

    • Pros: at automatically throws an error if the key does not exist
    • Cons: try-catch is apparently fairly costly and also constrains what the optimizer can do with the code
  • Use find

    • Pros: One call, no try-catch overhead
    • Cons: Involves using an iterator; more overhead than just returning the value
    auto findit = myMap.find(id);      if(findit == myMap.end())      {        //error message;        exit(74);       }      else      {        return findit->first;      }  

ErrorException undefined array key "GET"

Posted: 18 Feb 2022 07:48 AM PST

I was running my Laravel application and got this error suddenly, and I'm not sure of how to solve this. I was running this on the server. Here is the detailed exception that I was getting.

Illuminate\Foundation\Bootstrap\HandleExceptions::handleError C:\xampp\htdocs\redprixx\routes\api.php:19

api.php

Route::get('/', function (Router $router) {      return collect($router->getRoutes()->getRoutesByMethod()["GET"])          ->map(function ($value, $key) {          return url($key);      })->values();  });  

Using multi-match query across parent and nested documents possible?

Posted: 18 Feb 2022 07:48 AM PST

Assuming the model:

{    "group" : "fans",    "name": "Anne",    "user" : [      {        "first" : "John",        "last" :  "Smith"      },      {        "first" : "Alice",        "last" :  "White"      }    ]  }  

with user being of "nested" type, I would like to use multi-match query to select matching documents (and inner hits) that match on both parent and innerhit.

Use case 1 - all match on parent

Searching fans Anne should give me the above document along with all inner hits because it matches completely on the parent level.

Use case 2 - all match on inner hit

Searching John Smith should give me the above document, but only with the first inner hit because it did not match on parent level nor did it match on the second inner hit.

Use case 3 - partial match on parent and inner hit

Searching fans Smith should give me the above document, but only with the first inner hit because the combined result matches in combination with the parent and first inner hit fields. It should NOT return the second inner hit since Smith is missing from both its own and parent fields.


Use cases 1 and 2 are quite easily solved with a boolquery that joins together a multi-match query on the parent level and another multi-match query inside a nested query (following is Java code):

boolQuery()      .should(multiMatchQuery(searchTerm).operator(AND).type(CROSS_FIELDS))      .should(nestedQuery("user", multiMatchQuery(searchTerm).operator(AND).type(CROSS_FIELDS), NONE))  

It's the third use case that I am stuck on. The above query only works for the parent level or nested level separately, but not in combination. I have tried to add "include_in_parent" to the nested type to have it indexed together with the parent, but then it matches on searches like John Alice which I don't want.

How to add Onclick listener to recycler view

Posted: 18 Feb 2022 07:49 AM PST

I am developing a simple notepad app first i used listView to show all the notes.But now I am using RecyclerView. While i am using listview i used OnItemClickListener to pass the Data to another activity for editing the note now i am confuse what to do in Recylerview

For listView i am using this

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {          @Override          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              name = filenames.get(position).getName();              note = filenames.get(position).getShorttext();              Alert(); // this method is in main activity             }      });*/          public void Alert()     {      final AlertDialog dialog;      View mview = getLayoutInflater().inflate(R.layout.dialog_pass,null);      final EditText mEdittext = (EditText) mview.findViewById(R.id.Epass);      AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);      mBuilder.setView(mview);      mBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {          @Override          public void onClick(DialogInterface dialog, int which) {              String col = mEdittext.getText().toString();              String password = dBhelper.searchpass(col);              if (col.equals(password)) {                  Intent intent =  new Intent(MainActivity.this,Note2.class);                  intent.putExtra("Name",name);                  intent.putExtra("Note",note);                  startActivity(intent);              } else {                  Toast temp = Toast.makeText(MainActivity.this, "Password does not match", Toast.LENGTH_SHORT);                  temp.show();              }            }      });      mBuilder.setNegativeButton("Cancel",null);      mBuilder.setCancelable(false);      dialog = mBuilder.create();      dialog.show();         }  

Now What Should i Do for Recycle View Please Help

  public class RecycleViewAdapter extends     RecyclerView.Adapter<RecycleViewHolder> {// Recyclerview will extend to    private List<FileName> fileNames;    private Context context;      public RecycleViewAdapter(Context context,List<FileName> fileNames) {      this.context = context;      this.fileNames = fileNames;  

}

@Override  public RecycleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {      LayoutInflater mInflater = LayoutInflater.from(parent.getContext());        ViewGroup mainGroup = (ViewGroup) mInflater.inflate(              R.layout.grid_item, parent, false);      RecycleViewHolder listHolder = new RecycleViewHolder(mainGroup);      return listHolder;    }    @Override  public void onBindViewHolder(RecycleViewHolder holder, final int position) {      final FileName model = fileNames.get(position);      RecycleViewHolder mainHolder = (RecycleViewHolder) holder;// holder      mainHolder.title.setText(model.getName());      mainHolder.note.setText(model.getShorttext());    }    @Override  public int getItemCount() {      return (null != fileNames ? fileNames.size() : 0);    }  

What exactly is a Release in GitHub?

Posted: 18 Feb 2022 07:48 AM PST

  • What is it exactly?
  • For what is it used?
  • How widespread is the usage?
  • How is it usually used?

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Posted: 18 Feb 2022 07:48 AM PST

I am running Windows Vista and am attempting to connect via https to upload a file in a multi part form but I am having some trouble with the local issuer certificate. I am just trying to figure out why this isnt working now, and go back to my cURL code later after this is worked out. Im running the command:

openssl s_client -connect connect_to_site.com:443  

It gives me an digital certificate from VeriSign, Inc., but also shoots out an error:

Verify return code: 20 (unable to get local issuer certificate)  

What is the local issuer certificate? Is that a certificate from my own computer? Is there a way around this? I have tried using -CAfile mozilla.pem file but still gives me same error.

No comments:

Post a Comment