Friday, May 21, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to send array to post api in javascript

Posted: 21 May 2021 09:06 AM PDT

I have a basketProducts Object array and I want to pass it to a POST getBasketTotal api

Doing console.log(basketProducts) I receive [{"barcode": "80582588", "quantity": 1}]

But when I call the api

const basketTotalResponse = await api.getBasketTotal(   {                                                              items: JSON.stringify(basketProducts)   }  )  

data passed in request is this

items=%5B%7B%22barcode%22%3A%2280582588%22%2C%22quantity%22%3A1%7D%5D  

resulting in an error 500.

Why I don't get a correct request data values as [{"barcode": "80582588", "quantity": 1}] ?

I've tried with and without JSON.stringify() but api request is always the same

Laravel Request has array but iteration error "Trying to get property 'product' of non-object"

Posted: 21 May 2021 09:06 AM PDT

When I used

return $request->all();  

network preview tab

  0 => array:10 [      "id" => 1      "user_id" => 1      "product_id" => 1      "brand_id" => 1      "quantity" => 2      "total" => "90000"      "created_at" => "2021-05-21T07:48:34.000000Z"      "updated_at" => "2021-05-21T07:48:34.000000Z"      "product" => array:10 [        "id" => 1        "name" => "S1 Pro"        "category_id" => 1        "sub_category_id" => 1        "brand_id" => 1        "buy_price" => "40000.00"        "sell_price" => "45000.00"        "description" => "this is a new phone"        "created_at" => "2021-05-20T06:02:28.000000Z"        "updated_at" => "2021-05-20T06:02:28.000000Z"      ]      "brand" => array:4 [        "id" => 1        "name" => "Vevo"        "created_at" => "2021-05-20T05:48:01.000000Z"        "updated_at" => "2021-05-20T05:48:01.000000Z"      ]    ]    1 => array:10 [      "id" => 2      "user_id" => 1      "product_id" => 2      "brand_id" => 2      "quantity" => 1      "total" => "195000"      "created_at" => "2021-05-21T08:49:47.000000Z"      "updated_at" => "2021-05-21T08:49:47.000000Z"      "product" => array:10 [        "id" => 2        "name" => "Note 20 ultra"        "category_id" => 1        "sub_category_id" => 2        "brand_id" => 2        "buy_price" => "180000.00"        "sell_price" => "195000.00"        "description" => "A new phone a new Era"        "created_at" => "2021-05-21T06:39:43.000000Z"        "updated_at" => "2021-05-21T06:39:43.000000Z"      ]      "brand" => array:4 [        "id" => 2        "name" => "Samsung"        "created_at" => "2021-05-21T06:37:54.000000Z"        "updated_at" => "2021-05-21T06:37:54.000000Z"      ]    ]  ]  

But when Im using foreach loop to access every item it give error of "Trying to get property 'product' of non-object"

method I'm using

    public function sellProduct(Request $request){          // dd($request->all());              $cardData = $request->all();              foreach ($cardData as $value) {                  return $value->product;              }      }  

please help to resolve this issue, basically I'm creating a cart app through request I'm getting all the details and product

iterating with while loop: adds slightly more than I'm asking for

Posted: 21 May 2021 09:06 AM PDT

I'm working in Python. So before I start my loop, I have s=3 and ds=0.2. I have a while loop ending at s=5. At the end of the loop, s+=ds. At each iteration of the loop I'm plotting my graph for that time, and values weren't exactly right, and when I included the times in title of the graphs, I saw they're not exact. I'm getting this:

3  3.2  3.4000000000000004  3.6000000000000005  3.8000000000000007  4.000000000000001  4.200000000000001  4.400000000000001  4.600000000000001  4.800000000000002  

What's with that? How can I make it not do that? I'm thinking it might have to do with the type-- obviously I can't just use "int" of s, but I might try to round it to one decimal place. Currently the differences are actually slightly visible. Thanks in advance.

Why is D'Esopo-Pape algorithm not used more often for finding shorthest paths?

Posted: 21 May 2021 09:06 AM PDT

D'Escopo-Pape algorithm is very similar in implementation to the Dijkstra's algorithm and works with negative weight edges but it doesn't work with negative cycles. It is apparently faster then Dijkstra's algorithm and Bellman-Ford algorithm in most cases. So why isn't it used more often when problem requires such type of task? Also there is apparently special cases where this algorithm takes exponential time, can someone provide some example or point me to some material that analyses this algorithm more thoroughly.
This is the implementation:

struct Edge {      int to, w;  };    int n;  vector<vector<Edge>> adj;    const int INF = 1e9;    void shortest_paths(int v0, vector<int>& d, vector<int>& p) {      d.assign(n, INF);      d[v0] = 0;      vector<int> m(n, 2);      deque<int> q;      q.push_back(v0);      p.assign(n, -1);        while (!q.empty()) {          int u = q.front();          q.pop_front();          m[u] = 0;          for (Edge e : adj[u]) {              if (d[e.to] > d[u] + e.w) {                  d[e.to] = d[u] + e.w;                  p[e.to] = u;                  if (m[e.to] == 2) {                      m[e.to] = 1;                      q.push_back(e.to);                  } else if (m[e.to] == 0) {                      m[e.to] = 1;                      q.push_front(e.to);                  }              }          }      }  }  

This is the link of the site i used: D'Esopo-Pape
Which doesn't really go in depth in terms of special cases and time-complexity.

Notice: Undefined index: steamid on line 17

Posted: 21 May 2021 09:06 AM PDT

I am attempting to resurrect an outdated file that I have. My PHP version is 7.3.21 and SQL is 5.02

I also get this

( ! ) Fatal error: Uncaught Error: Call to undefined function mysql_query() on line 19

what wisdom would this community give in this since most of this is obsolete?

thanks!

<?php        $connection = mysqli_connect("localhost", "admin", "password"); // Change this line to your information.    if (!$connection) {      error_log("Failed to connect to MySQL: " . mysqli_error($connection));      die('Internal server error');  }    // 2. Select a database to use   $db_select = mysqli_select_db($connection, "gmod_perp");  if (!$db_select) {      error_log("Database selection failed: " . mysqli_error($connection));      die('Internal server error');  }        $steamid = $_GET["steamid"]; //line 17    $q = mysql_query("SELECT * FROM `smf_members_pending` WHERE `steamid`='" . $steamid ."' LIMIT 1"); //line 19    if (!$q){ die('b'); }    ?>  

How to transfer data to another sheet based on cell value?

Posted: 21 May 2021 09:06 AM PDT

I have the code below that returns "Syntax error: SyntaxError: Unexpected token '{ line: 22 file: Code.gs" and I can't figure out why.

This workbook has a vlookup(importrange in column B which triggers column "O" to change from a null value to "Received". Once that that particular cell = "Received" it should copy that row to the tab named "Received" and delete it from the Master tab.

   SpreadsheetApp.getUi().createMenu('New Menu') {    .addItem('Run', 'doneCopy')    .addToUi()  }    function doneCopy() {   var ss=SpreadsheetApp.getActive();   var sheet=SpreadsheetApp.getActiveSheet();   var range=sheet.getActiveCell();   if (sheet.getName()=="Master" && range.getColumn()==15 && range.getValue()=="Received") {     var targetSheet=ss.getSheetByName("Received");     var targetRange=targetSheet.getRange(targetSheet.getLastRow() + 1, 1);     sheet.getRange(range.getRow(), 1, 1, sheet.getLastColumn()).moveTo(targetRange);     sheet.deleteRow(range.getRow());   }  }  

Any idea what is causing this error?

Creating new objects versus encoding data in primitives

Posted: 21 May 2021 09:05 AM PDT

Let's assume I want to store (integer) x/y-values, what is considered more efficient: Storing it in a primitive value like long (which fits perfect, due sizeof(long) = 2*sizeof(int)) using bit-operations like shift, or and a mask, or creating a Point-Class?

Keep in mind that I want to create and store many(!) of these points (in a loop). Would be there a perfomance issue when using classes? The only reason I would prefer storing in primtives over storing in class is the garbage-collector. I guess generating new objects in a loop would trigger the gc way too much, is it correct?

Prevent infinite loop in useEffect when setting state

Posted: 21 May 2021 09:05 AM PDT

I am currently building a scheduling app. If a user selects two dates, I am attempting to select all date blocks between the two selected dates in the calendar as well. I am able to achieve this, but it causes my useEffect to fire into an infinite loop because I have state as a dependency in my useEffect where I am setting state. I am unsure of the best method to prevent the infinite loop behavior. The useEffect in question is the bottom one. My code is as follows:

export default function App() {    const [selectedDate, handleDateChange] = useState(      dayjs().format("YYYY-MM-DD")    );    const [events] = useState([      {        id: "5e24d1fa-aa66-4122-b1eb-97792f0893b0",        name: "Rodriquez Family",        selectedDates: ["2021-05-01"],        status: "submitted"      },      {        id: "269a0381-63c7-4ab6-92d8-7f7b836aee6f",        name: "Test Family",        selectedDates: ["2021-05-03"],        status: "submitted"      }    ]);    const [data, setData] = useState([]);      const getDaysArray = async (firstDay, lastDay) => {      let dates = [];      var dow = dayjs(firstDay).day();      while (dow > 0) {        dates.push(null);        dow = dow - 1;      }        while (firstDay <= lastDay) {        dates.push(firstDay);        firstDay = dayjs(firstDay).add(1, "days").format("YYYY-MM-DD");      }        return dates;    };      useEffect(() => {      const getDates = async () => {        const firstDay = dayjs(selectedDate)          .startOf("month")          .format("YYYY-MM-DD");        const lastDay = dayjs(firstDay).endOf("month").format("YYYY-MM-DD");        const dates = await getDaysArray(firstDay, lastDay);          const list = dates.map((date) => {          const event = events.find(({ selectedDates = [] }) =>            selectedDates.includes(date)          );          return event ? { date, event } : { date, event: null, checked: false };        });          setData(list);      };      getDates();    }, [events, selectedDate]);      const selectDate = (date) => {      setData(        (a) =>          a &&          a.map((item) =>            item.date === date ? { ...item, checked: !item.checked } : item          )      );    };      useEffect(() => {      if (data && data.filter((res) => res.checked).length > 1) {        const filterDates = data.filter((r) => r.checked);        const startDate = filterDates[0].date;        const endDate = filterDates[filterDates.length - 1].date;          const datesToUpdate = data.filter(          (res) => res.date > startDate && res.date < endDate        );          const newArr = data.map((date) => {          const updateCheck = datesToUpdate.find((r) => r.date === date.date);            return updateCheck ? { ...updateCheck, checked: true } : date;        });          setData(newArr);      }    }, [data]);      return (      <MuiPickersUtilsProvider utils={DayJsUtils}>        <div className="App">          <DatePicker            minDate={dayjs()}            variant="inline"            openTo="year"            views={["year", "month"]}            label="Year and Month"            helperText="Start from year selection"            value={selectedDate}            onChange={handleDateChange}          />        </div>        <div className="cal">          <div className="cal-div1"></div>          <div className="cal-div2 "></div>          <div className="cal-div3 cal-cir-hov"></div>          <div className="cal-div4"> SUN </div>          <div className="cal-div5"> MON </div>          <div className="cal-div6"> TUE </div>          <div className="cal-div7"> WED </div>          <div className="cal-div8"> THU </div>          <div className="cal-div9"> FRI </div>          <div className="cal-div10"> SAT </div>          {data &&            data.map((r, i) => {              return (                <>                  <div                    onClick={() =>                      !r.checked &&                      r.date >= dayjs().format("YYYY-MM-DD") &&                      !r.event &&                      selectDate(r.date)                    }                    style={                      r.checked                        ? { backgroundColor: "green" }                        : { color: "#565254" }                    }                    key={i}                    className="cal-cir-hov"                  >                    <div>{r.date} </div>                    <div                      style={                        r.event?.status === "submitted"                          ? { color: "orange" }                          : { color: "green" }                      }                    >                      {r.event?.name}                    </div>                  </div>                </>              );            })}        </div>      </MuiPickersUtilsProvider>    );  }    

attached is a code sandbox for debugging and to show the behavior I am currently talking about. Select two separate dates that are greater than today and you will see all the dates in between are selected, but the app goes into a loop https://codesandbox.io/s/dawn-snow-03r59?file=/src/App.js:301-4499

Im having a problem about this one. I am new at laravel. How can i route in my desired pages using this code

Posted: 21 May 2021 09:05 AM PDT

<select class="form-control" id="usertype" name="usertype">    <option>Admin</option>    <option>Student</option>    ...  

How can I route to other pages if I select Admin and also in student. Thank you.

Regex for abbreviation doesn't work properly in csv file

Posted: 21 May 2021 09:05 AM PDT

I want to replace the abbreviation "etc." in a csv file with its full form "et cetera". The csv test file can be seen below:

# Audio_Filename|Segment_Text  fa73f311.wav|I'd like to buy shoes, clothes, etc.  fa73f311.wav|I'd like to buy shoes, clothes etc.  fa73f311.wav|I'd like to buy shoes, clothes, etc..  fa73f311.wav|I'd like to buy shoes, clothes etc..  fa73f311.wav|I'd like to buy shoes, clothes, etc. but I'm broke.  fa73f311.wav|I'd like to buy shoes, clothes etc. but I'm broke.  fa73f311.wav|I'd like to buy shoes, clothes etc., but I'm broke.  

With my current code, only the abbreviations in the middle of the sentence get replaced but not at the end of a sentence. I want to match all of the "etc." in this file.

With a regex tester, all "etc." are correctly matched, but my code results in omitting the punktuation mark at the end of the sentences or after the abbreviation itself (probably due to the grouping in my code). I have tried many other options but nothing works as desired. How can I get this right?

Any hint is much appreciated, thanks!

My code:

import re   import pandas as pd    # Read file into dataframe.  with open('/home/user/data/test.csv') as f:      df = pd.read_csv(f, names=['Audio_Filename', 'Segment_Text'], sep='|')      # Replace abbreviation.      df['Segment_Text'].replace(to_replace=r'(\W)?( )?etc\.( )?(\W|\d)', value=r'\1 et cetera \4', regex=True, inplace=True)      # Write dataframe to new file.      df.to_csv('/home/user/data/test_replaced.csv',                header=False, index=False, sep='|')    

Result:

fa73f311.wav|I'd like to buy shoes, clothes, etc.  fa73f311.wav|I'd like to buy shoes, clothes etc.  fa73f311.wav|I'd like to buy shoes, clothes, et cetera.  fa73f311.wav|I'd like to buy shoes, clothes et cetera.  fa73f311.wav|I'd like to buy shoes, clothes, et cetera but I'm broke.  # works  fa73f311.wav|I'd like to buy shoes, clothes et cetera but I'm broke.  # works  fa73f311.wav|I'd like to buy shoes, clothes et cetera, but I'm broke.  # works  

Desired result:

fa73f311.wav|I'd like to buy shoes, clothes, et cetera.  fa73f311.wav|I'd like to buy shoes, clothes et cetera.  fa73f311.wav|I'd like to buy shoes, clothes, et cetera..  fa73f311.wav|I'd like to buy shoes, clothes et cetera..  fa73f311.wav|I'd like to buy shoes, clothes, et cetera but I'm broke.  fa73f311.wav|I'd like to buy shoes, clothes et cetera but I'm broke.  fa73f311.wav|I'd like to buy shoes, clothes et cetera, but I'm broke.  

How to avoid TLE error and optimize this C++ problem?

Posted: 21 May 2021 09:06 AM PDT

I am passing all the test cases but getting a TLE error in the final submission.Need some help optimizing it.

QUESTION

An infectious disease is spreading in a city. The Mayor of the city wants to take strict action to provide proper prevention from the disease.

There are N persons in the city who stay side by side in increasing order of their index, that is, the ith person has the (i - 1)th and (i

  • 1)th person staying next to him or her.

Initially, it is found that among N persons, exactly M are infected with the disease. Further, it was found the disease is contagious, and it spreads from an infected person to his or her neighbours. It means that if the ith person is infected, then the (i - 1)th person and (i + 1)th person staying just next to the ith person can get infected from him or her.

Also, it is observed that people who are not infected(people apart from initial M infected people) get infected in a particular sequence. This sequence provides the order in which people(who are not infected) get infected with the increasing span of time. It may be possible that the xth person gets infected only after the yth person and this defines a particular order among them, that it, y must always be placed before x in the sequence. For example, N = 6 and person 3 and 5 are infected. Here, person 2 gets affected before person 1. Similarly, person 2 and 4 can be placed with any relative order as they can get infected from 3 directly.

The Mayor wants you to determine the number of unique sequences in which the other persons can get infected. Since the answer can be large, print it modulo 1000000007 (10^9 + 7).

Note: Two sequences are said to be different if there exists at least one position among sequences where a person present is different.

Input format

The first line contains two space separated integers N and M The next line contains M space-separated integers denoting integers denoting infected people. Output format Print a single integer denoting the number of unique sequences.

Constrains 1 <= N <= 2 * 10 ^ 5 1 <= M <= N - 1

Sample Input 1

5 2    1 5    

Sample Output 1

4  

Explanation

Person 2 and 4 can get infected from Person 1 and 5 respectively. Person 3 can only get infected after either Person 2 or 4 get infected.

The possible sequences are as follows:    [2, 3, 4]    [2, 4, 3]    [4, 3, 2]    [4, 2, 3]  

Solution I made:

Using DP and storing the states as a string of 1 and 0

State = string of length n representing n person and their state of infection( 1 if the person is infected else 0) dp[State] = no of paths to final State of all 1's (111....) from State dp[11....1] = 1

Eg : if n=5 and 1 st,5 th person are infected Paths in the recursion trees

10001 : initial state    path 1 : 10001 -> 11001 -> 11101 -> 11111    path 2 : 10001 -> 10011 -> 11011 -> 1111    path 3 : 10001 -> 10011 -> 11011(overlapping sub problem)    path 4 : 10001 -> 10011 -> 10111 -> 11111      public class Solution {      public static HashMap<String,Integer> dp = new HashMap<>();        public static void main(String[] args) {          int n = 5;          // 1 st and 5 th person are infected so initial state = 10001          dp.put("11111",1);          System.out.println(findPosSequences("10001"));      }            public static int findPosSequences(String state) {          if(dp.containsKey(state))              return dp.get(state);                    int pos = 0;          boolean vis[] = new boolean[state.length()];          for(int i=0;i<state.length();i++) {              if(state.charAt(i)=='1') {                  if(i-1>=0 && state.charAt(i-1)=='0' && !vis[i-1]) {                      String updatedState = state.substring(0,i-1)+"1"+state.substring(i);                      vis[i-1] = true;                      pos += findPosSequences(updatedState);                  }                  if(i+1<state.length() && state.charAt(i+1)=='0' && !vis[i+1]) {                      String updatedState = state.substring(0,i+1)+"1"+state.substring(i+2);                      vis[i+1] = true;                      pos += findPosSequences(updatedState);                  }              }          }          System.out.println(state+" "+pos);          dp.put(state,pos);          return pos;      }  }  

Complexity of Program: time complexity : O(N* 2^(N-M)) space complexity : O(2^(N-M))

How to get values of dynamic textareas in vue js?

Posted: 21 May 2021 09:06 AM PDT

I am creating text fields inside the v-for loop Now confusion is how I can get values of all these inputs those are not fixed number input so I can set their variables in data()

How i am rendering inputs

  <ion-list>          <ion-item v-for="(worker, index) in this.workers" :key="index">            <ion-label text-wrap>              {{ worker.name }}            </ion-label>             <ion-textarea placeholder="Enter Detail..."></ion-textarea>          </ion-item>        </ion-list>          <section style="margin: 20px 30px;--color: #272727;"></section>        <section>          <ion-button            shape="round"            expand="full"            @click="submit"            style="--background: #272727;text-transform: capitalize;font-size: 16px;color: #ffc946;"          >Submit</ion-button>          <!-- Save -->        </section>    

In submit() method i want to fetch values of all these textareas

How do I write a Java program for random multiplcation?

Posted: 21 May 2021 09:05 AM PDT

Here is the question: "Write a program that helps to teach elementary kids multiplication. The kids are asked to multiply 2 random numbers and provided an answer. The random numbers can range from 1 to 12. Once the program has asked them 10 questions, it prints the percentage they got correct." I know how to work with the random number method but I don't know how to ask the user this correctly.

JsFiddle URL with trailing slash being evaluated as correct link

Posted: 21 May 2021 09:06 AM PDT

I wrote a small method that evaluates JSFiddle snippet URLs.

A valid JSFiddle snippet URL looks like this: https://jsfiddle.net/BideoWego/y200sqpr/ or https://jsfiddle.net/BideoWego/y200sqpr.

An invalid URL is anything else.

It seems to work well, but for some strange reason it evaluates https://jsfiddle.net/BideoWego/ to true. How can I fix this.

// this should evaluate to false  console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/"));    // this should evaluate to true  console.log(checkCourseContentElementCodeFiddleUrl("https://jsfiddle.net/BideoWego/y200sqpr/"));    function checkCourseContentElementCodeFiddleUrl(url) {      return !!url.match(/((\/\/\/?|https?:\/\/)?(www\.)?jsfiddle\.net\/.+\/.?([?#].*)?)/gi);    }

How to display a column when a variable is true in Flutter?

Posted: 21 May 2021 09:05 AM PDT

I keep getting this error that res is not defined, so I am trying to figure out how to run the column code after res is defined like in js you can do {res && (code)}.

Column(   children: res['rooms'].map((r) => Card(        'name',        '${r['messages'][r['messages'].length - 1]['content']}',        '${r['_id']}'   )),  ),  

How can I refactor this long chain of similar promises

Posted: 21 May 2021 09:06 AM PDT

How can I refactor the following code? For context, this is from cloudflare workers.

// Instantiate rewriter.  const rewriter = new HTMLRewriter()  .on('link', new AttributeHttpsRewriter('href'))  .on('img', new AttributeHttpsRewriter('src'))  .on('form', new AttributeHttpsRewriter('action'))  .on('script', new AttributeHttpsRewriter('src'))  .on('a', new AttributeHttpsRewriter('href'))  .on('iframe', new AttributeHostRewriter('src'))  .on('link', new AttributeHostRewriter('href'))  .on('link[rel="canonical"]', new AttributeHostRewriter('href'))  .on('link[rel="shortlink"]', new AttributeHostRewriter('href'))  .on('a', new AttributeHostRewriter('href'))  .on('meta', new AttributeHostRewriter('content'))  .on('form', new AttributeHostRewriter('action'))  .on('iframe', new AttributeHostRewriter('src'))  .on('textarea.clipboard-target',new TextHostRewriter());  

I feel like it should be possible to have an object like:

{attributeRewriter: {'link':'href','img':'src','form':'action'} etc... }  

And iterate through it. Is it as simple as calling

 rewriter.on(class,rewriter)  

for each?

Is this even desirable?

How to run an ASP.NET Web Application (.NET Framework) outside IDE?

Posted: 21 May 2021 09:06 AM PDT

I used to make REST APIs using the "ASP.NET Core Web Application" template in Visual Studio 2019, but I don't want to have to install .NET Core to use my server application, so I used the .NET Framework template.

However, the former always created an executable file for me to run even outside the IDE. The server would run in a console window. The .NET Framework template however only generates the assembly as a DLL. There is no use in changing to "Console Application" in project settings since the template has no Main() function.

How would I make my server run outside the IDE? I'd love to know how to get the server started from a Main() function. I could then implement a ServiceBase class to turn my program into a service, which is ultimately what I want.

I know that there is a way to "deploy" the server to run with issexpress, but I'd rather have it run itself from an executable.

What will be the output, if we print a boolean variable which is assigned a value 0? Ex: boolean test = 0; [closed]

Posted: 21 May 2021 09:05 AM PDT

What will be the output, if we print a boolean variable which is assigned a value 0?

Ex: boolean test = 0;

public class RandomTest {      public static void main(String[] args) {                boolean isJavaFun = 1;          System.out.println(isJavaFun);        }  }  

Select ID of a row with max value

Posted: 21 May 2021 09:06 AM PDT

How can I select the ID of a row with the max value of another column in a query that joins multiple tables?

For example, say I have three tables. tblAccount which stores a grouping of users, like a family. tblUser which stores the users, each tied to a record from tblAccount. And each user can be part of a plan, stored in tblPlans. Each plan has a Rank column that determines it's sorting when comparing the levels of plans. For example, Lite is lower than Premium. So the idea is that each user can have a separate plan, like Premium, Basic, Lite etc..., but the parent account does not have a plan.

How can I determine the highest plan in the account with a single query?

tblAccount

PKID Name
1 Adams Family
2 Cool Family

tblUsers

PKID Name AccountID PlanID
1 Bob 1 3
2 Phil 2 2
3 Suzie 2 1

tblPlans

PKID Name Rank
1 Premium 3
2 Basic 2
3 Elite 4
4 Lite 1

Here's the result I'm hoping to produce:

AccountID Name HighestPlanID PlanName
2 Adams Family 1 Premium

I've tried:

SELECT U.AccountID, A.Name, MAX(P.Rank) AS Rank, P.PKID as HighestPlanID, P.Name as PlanName  FROM tblPlans P  INNER JOIN tblUsers U ON U.PlanID = P.PKID  INNER JOIN tblAccounts A ON U.AccountID = A.PKID  WHERE U.AccountID = 2  

and the query will not always work, selecting the MAX of Rank does not select entire row's values from tblPlans.

I am looking for a solution that is compatible with mysql-5.6.10

Create Radio Button Xamarin forms in C# ONLY

Posted: 21 May 2021 09:06 AM PDT

Is it possible to create a Radio Button programmatically in C# in Xamarin forms in my shared project? Example you can create checkboxes like so: CheckBox Mybox = new CheckBox();

Sum of alias columns in PostgreSQL

Posted: 21 May 2021 09:05 AM PDT

SELECT COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END      END))        AS pending_with_documents,         COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no NOT IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END             END)) AS pending_without_documents,         COUNT(CASE                   WHEN status_code NOT IN ('ACK', 'INT', 'APR', 'REJ', 'SBK', 'OBJ') THEN                       ack_no             END)  AS Inprocessing  FROM application_ht_install  WHERE service_code IN (36);  

I need fourth column as total by summing up pending with documents + pending without documents + inprocessing How to achieve adding the count of these three alise columns but im getting an error couldn't find the column.

SELECT COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END      END))        AS pending_with_documents,         COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no NOT IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END             END)) AS pending_without_documents,         COUNT(CASE                   WHEN status_code NOT IN ('ACK', 'INT', 'APR', 'REJ', 'SBK', 'OBJ') THEN                       ack_no             END)  AS Inprocessing      SUM(pending_with_documents + pending_without_documents + Inprocessing)  FROM application_ht_install  WHERE service_code IN (36);  

So I tried

SELECT COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END      END))                             AS pending_with_documents,         COUNT(DISTINCT (CASE                             WHEN status_code IN ('ACK', 'INT') THEN                                 CASE                                     WHEN ack_no NOT IN                                          (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END             END))                      AS pending_without_documents,         COUNT(CASE                   WHEN status_code NOT IN ('ACK', 'INT', 'APR', 'REJ', 'SBK', 'OBJ')                       THEN ack_no END) AS Inprocessing      SUM((COUNT(DISTINCT(CASE WHEN status_code IN ('ACK','INT') THEN      CASE WHEN ack_no IN      (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END      END)) AS pending_with_documents )+ ( COUNT(DISTINCT(CASE WHEN status_code  IN ('ACK','INT') THEN      CASE WHEN ack_no NOT IN      (SELECT ack_no FROM bescom_appl_upload_doc) THEN ack_no END      END)) AS pending_without_documents)+ ( COUNT(CASE WHEN status_code NOT IN('ACK','INT','APR','REJ','SBK','OBJ') THEN      ack_no      END) AS Inprocessing))  FROM application_ht_install  WHERE service_code IN (36);  

getting error ERROR: syntax error at or near "sum" LINE 13: sum((count(distinct(case when status_code in ('ACK','INT') t... ^ SQL state: 42601 Character: 473

Delete With PDO Sqlserver

Posted: 21 May 2021 09:07 AM PDT

Morning, budies. I have an API call to bring me the profilesIds registereds in my websystem. I wanna make delete from my sqlserver table what is not content in my request response.

I do a select with the properties to show me what i have in common with my slqserver table and my response, and i do a delete with remaining.

In theory, it was supposed to work but no.

Have any mistake in sintax plz?

I currently have have 391 registers in my sql server table and only 389 is comum with my sqlserver table and response call. When i do a select, bring me only that registers in common, idk wasnt working.

Select Query (bring me only 389 registers that i mentioned, is right).

        $sql = "SELECT agentId, profileId                                  FROM LIVEPERSON_USERPROFILES                                  WHERE agentId = :agentId                                  AND profileId = :idProfile";                                            $stmt = Conexao::getConnection()->prepare($sql);      $stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);      $stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);      $rows = $stmt->execute();                    }      }  

Delete Query not working.

        $sql = "DELETE FROM LIVEPERSON_USERPROFILES                  WHERE NOT EXISTS (SELECT agentId, profileId                                    FROM LIVEPERSON_USERPROFILES                                    WHERE agentId = :agentId                                    AND profileId = :idProfile)";                                            $stmt = Conexao::getConnection()->prepare($sql);      $stmt->bindValue(":agentId",$agentId,PDO::PARAM_STR);      $stmt->bindValue(":idProfile",$idProfile,PDO::PARAM_STR);      $rows = $stmt->execute();                    }      }  

Data of table:

insert into testTable (agentId, profileId) values ('1536989','12345')  insert into testTable (agentId, profileId) values ('1536989','56789')  insert into testTable (agentId, profileId) values ('1536989','99999')  insert into testTable (agentId, profileId) values ('1536874','56789')  insert into testTable (agentId, profileId) values ('1536874','56984')  insert into testTable (agentId, profileId) values ('7568594','99999')  insert into testTable (agentId, profileId) values ('8895874','56984')  insert into testTable (agentId, profileId) values ('8895874','56789')  insert into testTable (agentId, profileId) values ('8895874','77777')  insert into testTable (agentId, profileId) values ('8895874','99999')  insert into testTable (agentId, profileId) values ('1235689','56789')  insert into testTable (agentId, profileId) values ('1235689','77777')  insert into testTable (agentId, profileId) values ('1245365','56984')  insert into testTable (agentId, profileId) values ('1245365','56789')  insert into testTable (agentId, profileId) values ('1245365','77777')  insert into testTable (agentId, profileId) values ('1245365','99999')  

Obs: One agentId can have multiples profileIds, so, agentId is duplicated. In data of table, i show that agentId 1536989 have a profile: 12345, 56789 and 99999. But in request, this agent have only 12345, 56789 profile. So i need delete from table the skill 9999.

Map with a multiple types of generic items for value

Posted: 21 May 2021 09:06 AM PDT

I have 3 different Set act as a cache and each serves for different reason. Additionally the keys are of different types e.g. Integer, String etc
I was thinking to create a wrapper class around this, but then I thought of just having them all as part of 1 hashmap and based on the key I can pick the proper Set
But I am not sure what is the proper way to do that.
I'd like to avoid something like:

private final Map<Integer, Set<Object>> cache = new HashMap<>();    public boolean exists(Integer type, Object key) {      return cache.get(type).contains(key);  }    public void addKey(Integer type, Object key) {      if(type == CACHE_1) {          Set<Object> set = cache.get(type);          if(set == null) {              set = new HashSet<>();              cache.put(type, set);          }          set.add(key);      }  }    

Is there a way to make it more type specific?

Update
These can be called as:

addKey(CACHE_1, "foo");    addKey(CACHE_2, 123);    

or

if(exists(CACHE_1, "foo")    if(exists(CACHE_2, 123)    

How do I consolidate several invoices that at one point were backordered and then fulfilled in mysql

Posted: 21 May 2021 09:05 AM PDT

For example I have a 1 invoice with 1 that was in stock and 3 that weren't in stock. Later on, the 2 invoices were created for those backordered ones. I want to be able to consolidate all those invoices into one displaying that 3 that were shipped and 1 that is still on backorder. mysql table is as follows:

order_id price model quantity previous_id
1788 1,200 SBS -1 Null //backordered
1788 1,200 SSC -1 Null //backordered
1788 1,200 SAC 1 Null
1788 1,200 SBB -1 Null //backordered

Second invoice

order_id price model quantity previous_id
1811 1,200 SBB 1 1788

Third invoice

order_id price model quantity previous_id
1865 1,200 SSC 1 1788

So as you can see previous_id tracks which was the original order for backordered items.

My mysql code is:

SELECT * FROM order_product where order_id = 1788 or previous_id = 1788 which displays all 6 rows but I want to be able to see 3 ordered and 1 backorder. Total should be showing 4 rows.

The final version should look like this:

order_id price model quantity previous_id
1788 1,200 SBS -1 Null //backordered
1788 1,200 SSC 1 Null
1788 1,200 SAC 1 1788
1788 1,200 SBB 1 1788

How do I achieve this?

removing index.php in ci4 but nothing happen

Posted: 21 May 2021 09:06 AM PDT

I changed in App.php public $indexPage = 'index.php'; To public $indexPage = ''; and public $uriProtocol = 'PATH_INFO'; and in .htaccess require realpath(FCPATH . ..'app/Config/Paths.php') ?: FCPATH . ..'/app/Config/Paths.php';

Problems downloading base64 as pdf JavaScript

Posted: 21 May 2021 09:05 AM PDT

I'm writing a Google Apps Script Web App, I'm facing a problem.

From server side I return the base64 encoded html code of a page:

function getRAW() {     var formText = 'https://www.google.com/';    var response = UrlFetchApp.fetch(formText);    var pdf1 = response.getAs('application/pdf');    //var myNewFile = DriveApp.createFile(pdf1);    var blob = response.getBlob()    var bytes = blob.getBytes();    var encoded = Utilities.base64Encode(bytes);    return encoded  }  

And that works well. Now, from client side, I want to download the base64 (is an html RAW content) as a pdf file (or .html if it is possible), but If I try to do like this I obtain a blank pdf page

function downloadRAW() {    var encoded = window.value;    var element = document.createElement('a');      element.setAttribute('href', 'data:application/pdf;base64,' + encoded);    element.setAttribute('download', 'prova');    element.style.display = 'none';    document.body.appendChild(element);      element.click();      document.body.removeChild(element);  }  

Note that If I try to obtain a text/plain;base64, works perfectly (return a .txt) file; but this is not what I want.

How can I achieve it?

Copy formatted table from doc1 to doc2

Posted: 21 May 2021 09:06 AM PDT

I have the function below which takes a table from an Excel spreadsheet, creates multiple arrays, formats a Word form and also modifies a Word document template to be used as an email when the from is complete.

I want to copy a table from the first Word document to the second at a bookmark location. I tried various methods. This last one I tried is supposed to select the first document, select the table and copy it to the second. It completes successfully, however it seems to take a cell from the Excel document.

objWord.Documents("C:\temp\DOC1.docm").Activate  objDoc.Tables(2).Range.Select  Selection.Copy          objWord.Documents(""C:\temp\DOC2.docm").Activate  Set bkRange = objDoc2.Bookmarks(bkProductionHistory).Range  bkRange.Paste  

Function FnOpenWordDoc(LastProdHist() As Variant, LastProdHistRow As Long, FileToSave As String) As Variant    Dim objWord  Dim objDoc  Dim objDoc2  Dim xPctComp As Long    Dim rRange As Word.Range        'MSword range  for Boook mark  Dim bkRange As Word.Range    Dim tblNew As Table             'Table Production History  Dim BkProdHist As String        'Bookmark varialble    Dim x, y, a, b  As Variant          BkProdHist = "BkProductionsHistory"                 'Production History Bookmark - Containes the complete productiosn histor in the first workd doc.      'bookmarks for the email document  bkUserName = "bkUserName"                           'bookmark Location for user name  BkVolume = "bkProductionVolume"                     'Bookmark Location for volume information in email  bkProductionDownload = "bkProductionDownload"       'Bookmark location for Download Link in email  bkProductionHistory = "bkProductionHistory"         'Bookmark location for Table copied from first word document  bkProductionSearch = "bkProductionSearch"           'Bookmark location for Production Seach  bkArchivePassword = "bkArchivePassword"             'Bookmark Locaion for Archive password      Set objWord = CreateObject("Word.Application")  Set objDoc = objWord.Documents.Open("C:\temp\DOC1.docm", ReadOnly:=True)  Set objDoc2 = objWord.Documents.Open(""C:\temp\DOC2.docm", ReadOnly:=True)    'objWord.Visible = False  objWord.Visible = True      objDoc.MailMerge.MainDocumentType = wdFormLetters  objDoc.MailMerge.OpenDataSource Name:= _  "C:\temp\DATA.XLSM", _  ConfirmConversions:=False, _  ReadOnly:=True, _  LinkToSource:=True, _  AddToRecentFiles:=False, _  PasswordDocument:="", _  PasswordTemplate:="", _  WritePasswordDocument:="", _  WritePasswordTemplate:="", _  Revert:=False, _  Format:=wdOpenFormatAuto, _  Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=C:\temp\DATA.XLSM;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:", _  SQLStatement:="SELECT * FROM `ProductionRequest$`", SQLStatement1:="", _  SubType:=wdMergeSubTypeAccess  objDoc.MailMerge.DataSource.ActiveRecord = wdLastRecord  objDoc.MailMerge.ViewMailMergeFieldCodes = wdToggle  'objDoc.MailMerge.Execute    If Dir(FileToSave) <> vbNullString Then      Kill FileToSave      'MsgBox "Deleted the file"  End If             '***************Create New Table With Production History - this is t first word doc   **********************  LastProdHistRow = LastProdHistRow + 6               ' Adding additional rows to production history table  Set rRange = objDoc.Bookmarks(BkProdHist).Range  Set tblNew = objDoc.Tables.Add(Range:=rRange, NumRows:=LastProdHistRow, NumColumns:=10)    objDoc.Tables(2).Cell(3, 1).Range.Text = "Date"  objDoc.Tables(2).Cell(3, 2).Range.Text = "Volume"  objDoc.Tables(2).Cell(3, 3).Range.Text = "Begin Bates"  objDoc.Tables(2).Cell(3, 4).Range.Text = "End Bates"  objDoc.Tables(2).Cell(3, 5).Range.Text = "Documents"  objDoc.Tables(2).Cell(3, 6).Range.Text = "Redactions"  objDoc.Tables(2).Cell(3, 7).Range.Text = "Pages"  objDoc.Tables(2).Cell(3, 8).Range.Text = "Images"  objDoc.Tables(2).Cell(3, 9).Range.Text = "Natives"  objDoc.Tables(2).Cell(3, 10).Range.Text = "Slip-Sheets"  objDoc.Tables(2).Cell(LastProdHistRow + 6, 4).Range.Text = "Totals"  '************** End - Create Table with Production History        'Begin************** Copy Production History Array to  Word Table *************************  'the loop only copies the first 10 columns of the array to the word table.    a = 4           ' The starting row of the table to begin copying data  For x = LBound(LastProdHist, 1) To UBound(LastProdHist, 1)      b = 1              For y = LBound(LastProdHist, 2) To UBound(LastProdHist, 2)                  If y <= 9 Then                      Debug.Print x, y, LastProdHist(x, y)                      objDoc.Tables(2).Cell(a, b).Range.Text = LastProdHist(x, y)                      b = b + 1                  End If              Next y      a = a + 1  Next x    'End**************  Produciton History Array to Word table ****************************       With objDoc.Tables(2)      .Range.Font.Size = 8      .Columns(2).Width = 40.5    'Date Column width      .Columns(3).Width = 81      'Begin Bates Column width      .Columns(4).Width = 81      'End Bates Colum width      .Columns(5).Width = 55      'Documents Column width      .Columns(6).Width = 55      'Redactions Column width      .Columns(7).Width = 37      'Pages Column width      .Columns(8).Width = 41      'Images Column width      .Columns(9).Width = 41      'Natives Column width      .Columns(10).Width = 62.5   'Slip-Sheet Column width      .Rows(LastProdHistRow).Range.Font.Bold = True      .Rows(3).Range.Font.Bold = True      .Rows(3).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter      .Cell(LastProdHistRow, 5).Formula Formula:="=Sum(Above)"      .Cell(LastProdHistRow, 6).Formula Formula:="=Sum(Above)"      .Cell(LastProdHistRow, 7).Formula Formula:="=Sum(Above)"      .Cell(LastProdHistRow, 8).Formula Formula:="=Sum(Above)"      .Cell(LastProdHistRow, 9).Formula Formula:="=Sum(Above)"      .Cell(LastProdHistRow, 10).Formula Formula:="=Sum(Above)"      .Rows(LastProdHistRow).Borders(wdBorderTop).LineStyle = wdLineStyleSingle      .Rows(LastProdHistRow).Borders(wdBorderBottom).LineStyle = wdLineStyleSingle      .Rows.SetLeftIndent LeftIndent:=-3.5, RulerStyle:=wdAdjustNone  End With     objDoc.Tables(2).Columns(1).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.Alignment = wdAlignParagraphRight  objDoc.Tables(2).Columns(2).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.Alignment = wdAlignParagraphCenter  objDoc.Tables(2).Columns(3).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.Alignment = wdAlignParagraphCenter  objDoc.Tables(2).Columns(4).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.Alignment = wdAlignParagraphCenter  objDoc.Tables(2).Columns(5).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.4), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces  objDoc.Tables(2).Columns(6).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.4), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces  objDoc.Tables(2).Columns(7).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.5), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces  objDoc.Tables(2).Columns(8).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.5), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces  objDoc.Tables(2).Columns(9).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.25), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces  objDoc.Tables(2).Columns(10).Select  Set ObjSelection = objWord.Selection  ObjSelection.ParagraphFormat.TabStops.Add Position:=InchesToPoints(0.4), Alignment:=wdAlignTabDecimal, Leader:=wdTabLeaderSpaces     With objDoc.Tables(2)      .Rows(2).Cells.Merge      .Cell(2, 1).Range.Text = "DOCUMENT PRODUCTION HISTORY"      .Cell(2, 1).Range.Style = ("Heading 1")      .Cell(LastProdHistRow, 4).Range.ParagraphFormat.Alignment = wdAlignParagraphRight      .Rows(LastProdHistRow - 2).Shading.ForegroundPatternColor = wdColorAutomatic      .Rows(LastProdHistRow - 2).Shading.BackgroundPatternColor = -553582797  End With          'Begin************** Setting up Email to send to  reqestor  *************************  '****  '**** objDoc2  has been opend for the this reason    Set bkRange = objDoc2.Bookmarks(bkUserName).Range  bkRange.Text = LastProdHist(LastProdHistRow - 6, 13)    Set bkRange = objDoc2.Bookmarks(BkVolume).Range  bkRange.Text = LastProdHist(LastProdHistRow - 6, 1)    Set bkRange = objDoc2.Bookmarks(bkProductionSearch).Range  bkRange.Text = LastProdHist(LastProdHistRow - 6, 10)    Set bkRange = objDoc2.Bookmarks(bkArchivePassword).Range  bkRange.Text = LastProdHist(LastProdHistRow - 6, 11)        Set bkRange = objDoc2.Bookmarks(bkProductionDownload).Range  bkRange.Text = LastProdHist(LastProdHistRow - 6, 12)    objWord.Documents("C:\temp\DOC1.docm").Activate  objDoc.Tables(2).Range.Select  Selection.Copy    objWord.Documents(""C:\temp\DOC2.docm").Activate  Set bkRange = objDoc2.Bookmarks(bkProductionHistory).Range  bkRange.Paste       'End**************** Setting up Email to send to  reqestor  *************************            'Debug.Print FileToSave    objDoc.ExportAsFixedFormat OutputFileName:= _      "C:\Temp\" & FileToSave, ExportFormat:=wdExportFormatPDF, _      OpenAfterExport:=True, OptimizeFor:=wdExportOptimizeForPrint, Range:= _      wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _      IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _      wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _      True, UseISO19005_1:=False  'ChangeFileOpenDirectory "C:\Temp\"      objDoc.MailMerge.DataSource.Close  'objDoc.Close SaveChanges:=wdDoNotSaveChanges  'objWord.Application.Quit  End Function  

How to install MySQL 5.7.x on Mac OS Sierra

Posted: 21 May 2021 09:06 AM PDT

I need to obtain the functionality of MySQL 5.7. I had zend server 9 (first 9 version). After reinstallation of zend server (it doesn't supports upgrade). - Result: MySQL 5.5 !

May there exist solutions for:

  • Upgrade mysql inside zend framework?
  • Install other apache2.4+mysql5.7+php7 developer server?
  • some other solution.

Requirements:

  • PHP7.0.8 or later
  • MySQL 5.7
  • Apache 2.4 or later

How can I update the parent's state in React?

Posted: 21 May 2021 09:05 AM PDT

My structure looks as follows:

Component 1     - |- Component 2       - - |- Component 4       - - -  |- Component 5    Component 3  

Component 3 should display some data depending on state of Component 5.

Since props are immutable, I can't simply save its state in Component 1 and forward it, right? And yes, I've read about Redux, but I don't want to use it. I hope that it's possible to solve it just with react. Am I wrong?

Unable to cast object of type 'System.DBNull' to type 'System.String`

Posted: 21 May 2021 09:05 AM PDT

I got the above error in my app. Here is the original code

public string GetCustomerNumber(Guid id)  {       string accountNumber =             (string)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidmyApp,                             CommandType.StoredProcedure,                             "GetCustomerNumber",                             new SqlParameter("@id", id));       return accountNumber.ToString();   }  

I replaced with

public string GetCustomerNumber(Guid id)  {     object accountNumber =              (object)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidCRM,                                   CommandType.StoredProcedure,                                   "spx_GetCustomerNumber",                                   new SqlParameter("@id", id));      if (accountNumber is System.DBNull)      {         return string.Empty;      }      else      {         return accountNumber.ToString();      }  }  

Is there a better way around this?

No comments:

Post a Comment