Sunday, August 8, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


EF DbSet.Local "order by" while maintaining synchronization

Posted: 08 Aug 2021 08:11 AM PDT

I had been looking for a solution to this for a month now with no definitive answer. Here is what I am trying to do.

(This is a simplification of my program). I am creating a WPF app in C#, using SQLite as a local database, with Entity Framework code first approach. In an MVVM manner.

This is my simplified app.

    public class MyDataContext : DbContext      {          public  MyDataContext() : base() { Database.EnsureCreated(); }            public DbSet<MyTable> myTable { get; set; }            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)          {              optionsBuilder.UseSqlite("Data Source=products.db");              optionsBuilder.UseLazyLoadingProxies();              base.OnConfiguring(optionsBuilder);          }            protected override void OnModelCreating(ModelBuilder builder) { }      }        public class MyTable: ObservableClass      {          int _Id; string _myString1, _myString2;            public int Id { get { return _Id; } set { if (_Id != value) { _Id = value; OnPropertyChanged(); } } }            public string myString1 { get { return _myString1; } set { if (_myString1 != value) { _myString1 = value; OnPropertyChanged(); } } }          public string mySrting2 { get { return _myString2; } set { if (_myString2 != value) { _myString2 = value; OnPropertyChanged(); } } }      }    public class Variables  {     public static globalDataContext = new MyDataContext();     // this is so I can have only ONE instance of the database, but I can access it from any window and it is Synchronized at all times.  }  
    public partial class MainWindow : Window      {          public MainWindow() { InitializeComponent(); DataContext = new WBinding(); }            class WBinding : ObservableClass          {              public BindingList<MyTable> myBindingTable { get { return globalVars.myDatacontext.myTable.Local.ToBindingList() } }              // THIS PART WORKS CORRECTLY AND IT IS IN SYNC ALL THE TIME BUT IT HAS NO QUERY OR ORDER              // The list is sync at all times, no matter in which windows I add/delete/modify items on the database.              // So I know the OnPropertyChanges are being raised for any and all actions on the database, because I can see the changes in this window at all times.          }      }  

Things I have tried (and A LOT of other tries from posts on the internet in general, which I can't remember right now):

    IOrderedEnumerable<MyTable> myOrderedTable = Variables.globalDataContext.myTable.Local.OrderBy(x => x.myString1);      // I get the correct order, but it looses sync with the database        BindingList<MyTable> myOrderedTable = new BindingList<MyTable>(Variables.globalDataContext.myTable.Local.OrderBy(x => x.myString1).ToList());      // I had great expectations with this one, the problem is that the only way I found that it lets me compile is with the "NEW BindingList<T>", which in fact creates a new list, which makes me lose the sync again.         BindingList<MyTable> myOrderedTable = new BindingList<MyTable>(Variables.globalDataContext.myTable.Local.ToBindingList().OrderBy(x => x.myString1).ToList());      // I don't know why I thought if I added "ToBindingList()" the result would be different, it is not, I still lose sync with the database.  

This is not my only problem, I also lose sync after a query.

    var myQuery = globalDataContext.myTable.Local.Where(x => x.myString1 == "Something");      // Query returns correctly, I lose sync.            var myQuery2 = globalDataContext.myTable.Local.Where(x => x.myString1 == "Something").First();      // Now THIS WORKS CORRECTLY, it returns ONE item of my database, the first that matches the query, and IT IS IN SYNC, if I modify this item, I can see it changing on other parts of the app, other windows mostly.  

I think both issues are related. I mean, I think I am doing the same wrong thing on both occasions. Any help is appreciated.

The only way I found that works, is if after adding/deleting/modifying an item I call "OnPropertyChanged" on the local variable so it can do the query/ordering again. But this is not always possible. Most of the times I am adding items from other windows, which the current window with the query or list is not aware of (and, if possible, I would like to keep it that way)

The interesting thing, is that in the variable myBindingTable, in MainWindow, it only does ToBindingList(), and THAT LIST IS IN SYNC WHEN QUERIES AND ORDERED LISTS ARE NOT, and I have no idea how to mirror that behaviour to a ordered list or query.

GCC 7.5.0, "no such file or directory" in Ubuntu when I enter ".contrib/download_prerequisites"

Posted: 08 Aug 2021 08:11 AM PDT

I'm trying to follow my Uni's tutorial, and none of my lecturers are active... I'm setting up GCC 7.5.0 in Ubuntu using Gitlab. I need to run the script ".contrib/download_prerequisites" from ~/source/gcc-7.5.0 before I can proceed, however it always responds with "bash: .contrib/download_prerequisites: No such file or directory".

Any ideas?

VSCODE: Paste with indentation relative to first line

Posted: 08 Aug 2021 08:11 AM PDT

When I try to copy/paste in vscode the result is not what i want:

I copy the lines with a, b and c:

def func():      a()      b()      c()  

When i then paste on a line with different indentation, it produces the following result:

a()      b()      c()  

but i want this:

a()  b()  c()  

That is, the relative indentation among the copied lines should stay the same.

Is there any way to achieve this? Thanks for any help! :)

How do I go from index 0 of my list to the next one flutter

Posted: 08 Aug 2021 08:11 AM PDT

my list in question is "idMap" and I have to make sure that when I press the button, it moves to the next index to the current one. is that id: id[0].toString() it also passes to the next index. any suggestions for moving to the next index ?

now I'm trying to recall the indexes but only with [0] I don't know how to manage it automatically

IconButton(                            onPressed: //TODO,                            icon: const Icon(                              Icons.arrow_back_ios_rounded,                            ),                          ),                        ),                        Expanded(                          flex: 2,                          child: Builder(builder: (context) {                            final List<int> id = [                              ContentBloc().state.userInfo.id,                              ...ContentBloc()                                  .state                                  .connectedUnits()                                  .map((e) => e.id),                            ];                            final idMap = id.asMap().entries.map((entry) {                              return entry.key;                            });                              final List<String> name = [                              // ignore: lines_longer_than_80_chars                              "${ContentBloc().state.userInfo.firstName} ${ContentBloc().state.userInfo.lastName}",                              ...ContentBloc()                                  .state                                  .connectedUnits()                                  .map((e) => e.storeName)                            ];                              final children = [                              ProfilePicture(                                key: ValueKey(idMap.toString()),                                size: 100,                                id: id[0].toString(),                                isUnit: false,                                showIcon: false,                                //withBorder: showArrows,                                //fit: showArrows ? null : BoxFit.contain,                              ),                              Padding(                                padding: const EdgeInsets.only(top: 18),                                child: Text(                                  name[0],                                  maxLines: 1,                                  overflow: TextOverflow.ellipsis,                                  style: const TextStyle(                                    fontSize: 19,                                    fontWeight: Fonts.medium,                                  ),                                ),                              ),                              IconButton(                                onPressed:                                    _identityController.value > idMap.length                                        ? () => _identityController                                            .call(_identityController.value)                                        : null,                                icon: const Icon(                                  Icons.arrow_forward_ios_rounded,                                ),                              ),  

Python Selenium won't click buttons when using an existing session of chrome

Posted: 08 Aug 2021 08:11 AM PDT

My python selenium code will no longer click on buttons when I use an existing session of Chrome. I have tested the exact same code if I don't run it on an existing session, and it works. I have tried reinstalling Chrome driver, but not sure how to fix this problem. Below is a very basic example that doesn't work. It navigates properly to the webpage, finds the button (it properly prints the text of the button), but won't click it. It does not give any error message, just doesn't click the button. I've tried this on other websites and get the same issue.

from selenium import webdriver  from selenium.webdriver.chrome.options import Options    PATH = "C:\Program Files (x86)\chromedriver.exe"    options = Options ()  options.add_experimental_option ("debuggerAddress", "127.0.0.1:8555")     driver = webdriver.Chrome(PATH, options = options)     url = "https://nbatopshot.com/moment/beelim23+ea9018ca-aee6-49f7-a96c-9a62eb0fddc2"      driver.get (url)      buy = driver.find_element_by_css_selector('[data-testid="mintedHeader-buy"]')      print (buy.text)      buy.click()  

If I run the exact same code like this, it does click the button in a new session of chrome:

from selenium import webdriver    PATH = "C:\Program Files (x86)\chromedriver.exe"    driver = webdriver.Chrome(PATH)     url = "https://nbatopshot.com/moment/beelim23+ea9018ca-aee6-49f7-a96c-9a62eb0fddc2"      driver.get (url)      buy = driver.find_element_by_css_selector('[data-testid="mintedHeader-buy"]')      print (buy.text)      buy.click()  

Unique clicks for Quick links

Posted: 08 Aug 2021 08:11 AM PDT

I have used a quick link from branch.io as a click through URL for an ad running via google ad manager. How do I get unique clicks for the quick link? Does unique click means unique user clicked on ad? Click numbers in google ad manager are not matching with the clicks recorded in branch. Please help me find out unique clicks for quick links

why adding bootstrap to angular is not working coorectly? nodejs

Posted: 08 Aug 2021 08:11 AM PDT

I am beginner in angular . trying to add bootstrap in my first project . but it doesn't appear below in the head section in developer tools . here is angularjson code.Thanks in advance

"architect": {          "build": {            "builder": "@angular-devkit/build-angular:browser",            "options": {              "outputPath": "dist/my-first-project",              "index": "src/index.html",              "main": "src/main.ts",              "polyfills": "src/polyfills.ts",              "tsConfig": "tsconfig.app.json",              "assets": [                "src/favicon.ico",                "src/assets"              ],              "styles": [                "node_modules/bootstrap/dist/css/bootstrap.css",                "src/styles.css"              ],              "scripts": [                "node_modules/bootstrap/dist/js/bootstrap.js"              ]  

Java method to return the second smallest odd value in array

Posted: 08 Aug 2021 08:10 AM PDT

I am troubling this question. Complete the following Java method to return the second smallest odd value for a given integer array. The array may contain duplicate values.

public int findSecondSmallestOdd(int[ ] data) { }

Can anyone help me

Writing data to a file and overwriting it using awk

Posted: 08 Aug 2021 08:10 AM PDT

I need to implement a script using awk instead of a sed using the example of the script below.

#!/bin/bash    FILE="data"    revoke_number() {      local number="$1"      while true      do          local pre_voice=$(sed -n "$number"'p' $FILE)          if [ -z $pre_voice ]          then          sed -i "$number"'c\0:'"$((number - 1))" $FILE          sed -i "$(( number + 1 ))"'s/.*//;' $FILE          number=$(( number - 1 ))      elif [ $number -eq 1 ]      then          break          else              sleep 10              echo "Sleep for 10"          fi      done  }  add_number() {      local second_line=$(sed -n '$=' $FILE)      echo $second_line      if [[ "$second_line" == "1" ]]      then          echo -e "0:$second_line" >> $FILE          echo "Exit"          exit 0      else      echo "To Revoke"      echo -e "0:$second_line" >> $FILE          revoke_number $second_line      fi  }  clear_empty_lines() {      local last_line=$(sed -n '$=' $FILE)      echo "THIS IS LAST $last_line"      for ((i=$last_line; i > 0; i--))      do          echo $i          values=$(sed -n "$i"'p' $FILE)          if [ -z $values ]          then              sed -i "$i"'d' $FILE          else              break          fi        done  }  clear_empty_lines  add_number  

The file the script is working with contains:

0:0  0:1  0:2  0:3  0:4  and etc.  

An example of how this script works: The file contains line 0:0. At startup, the script checks the last value, sees the value 0 and supplements the file with the 0:1 line (increases the last value by one).

Then the script is run again. He sees that the last value is 0:1 and writes the line 0:2. But the script does not stop working, but continues to check the file for the deletion of the line with the number 0:1 (the previous line). If we manually delete the 0:1 line in our text file, then the script should see the changes, delete the value 0:2 written by it and write 0:1 instead. This is how any run of this script will work. The value written at startup should check the previous value and, if it is deleted from the file, decrease its value by one, i.e. line 0:5 will check line 0:4 and if it is deleted it will overwrite its value from 5 to 4 and after rewriting it will check line 0:3. If line 0:3 is also deleted, it will overwrite 4 with 3 and check line 0:2.

For example, I launch a script, it added a value of 0:1 and went to sleep. I run the same script in another tab of the terminal, after launching it adds the value 0:2 and goes to sleep. After waking up from sleep, it rechecks the file again, and if script sees that I manually deleted the value 0:1 from the file, it deletes the 0:2 line and writes 0:1.

For example, if I run a script in the third tab, it will add the line 0:3, go to sleep and after waking up, it will check for the presence of line 0:2 and no other. If I delete the line 0:1, then the script launched in the second tab of the terminal should delete its value 0:3 and write 0:2 (since it checks the previous line and sees that it is free), and the script launched in the third terminal tab - it will see that the 0:2 line has been deleted (since it took the place of the 0:1 line I deleted) and will delete its value 0:3, writing the value 0:2 instead. The value increment line should be added only when the script is run for the first time; later it should check the file and parse the line that was written before it to see if it was deleted.

Step 1: Create a file with value 0:0

$ cat file.txt  0:0  

Step 2: Run the script that writes a value that is greater than the existing one and goes to sleep

$awk -i inplace 'NF{print "0:" c++} ENDFILE{if (c==NR) print "0:" c+0}' file.txt  $cat file.txt  0:0  0:1  

Step 3: Run the script in the second tab, which also adds a value 1 more than the one written in the last line and goes to sleep.

 $awk -i inplace 'NF{print "0:" c++} ENDFILE{if (c==NR) print "0:" c+0}' file.txt   $cat file.txt   0:0   0:1   0:2  

Step 4: Run the script in the third tab of the terminal, which also adds a value 1 more than the one written in the last line and goes to sleep.

$awk -i inplace 'NF{print "0:" c++} ENDFILE{if (c==NR) print "0:" c+0}' file.txt  $cat file.txt  0:0  0:1  0:2  0:3  

Step 5: Running scripts after waking up from sleep should reread the file. Step 6: Manually deletes the 0:1 line in the file.txt. The file looks like this:

$cat file.txt      0:0            0:2      0:3  

Step 7: The script that was launched in the second tab of the terminal after the next wake up sees that the line it is watching is free. And it overwrites its value there (decreasing by one). The file looks like this:

$cat file.txt      0:0      0:1            0:3  

Step 8: The script that was launched in the third tab sees that after waking up the line it was watching is empty. And it also writes its value to the vacated space (decreasing by one). The file looks like this:

$cat file.txt          0:0          0:1          0:2  

Step 9: If run the script in the fourth tab, it will again write the value one more than the one specified in the last line and will watch it.

$cat file.txt      0:0      0:1      0:2      0:3  

The script manipulates the data after 0: The file receives only the values that are written by the script at startup, and these are always numbers.

sort (order) posts by category name (title)

Posted: 08 Aug 2021 08:09 AM PDT

I have a parent category and 45-50 sub categories under that. I am trying sort posts by their child category name in archive pages on Wordpress.

By default, wordpress sort them by publishing date; i need them alphabetical (by their category name, NOT "post title")

Let's say A is parent category; i have 45-50 child category under A. And i need to sort posts which belongs to these categories. Order by child category name.

Collectionview dynamic height change with constraints not working in Swift

Posted: 08 Aug 2021 08:09 AM PDT

I am using collectionview in tableview cell and the hierarchy of tableview cell is like this

enter image description here

topview constraints top = 0, leading = 0, trailing = 0, bottom => 0

ViewX constraints top = 0 leading = 0, trailing = 0, bottom => 10

collectionviewViewX constraints top => 10 to ViewX, leading = 0, trailing = 0, bottom = 10

Attatchments collectionview constraints top = 10 to label, leading = 0, trailing = 0, bottom = 10, height = 50

Stackview constraints top = 10, leading = 0, trailing = 0, bottom = 10, height = 50

and tableview cell code: but with this code collectionview height is not changing according to cells count.. how to change collectionview height according to number of cells coming from JSON

 class ProposalTableVIewCell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource {    @IBOutlet weak var attCollHeight: NSLayoutConstraint!  @IBOutlet weak var attetchmentsCollectionview: UICollectionView!    override func awakeFromNib() {      super.awakeFromNib()            let layout = UICollectionViewFlowLayout()      layout.scrollDirection = .vertical            layout.minimumInteritemSpacing = 0            layout.minimumLineSpacing = 5      let width = UIScreen.main.bounds.width/2.5              let height = CGFloat(40)              layout.itemSize = CGSize(width: width, height: height)            self.attetchmentsCollectionview.collectionViewLayout = layout  }    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        return attachArray?.count ?? 0  }    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AttatchmentCollectionViewCell", for: indexPath) as! AttatchmentCollectionViewCell        var attatchBid = attachArray?[indexPath.item]        self.attCollHeight.constant = collectionView.contentSize.height        return cell  }    }  

o/p there are 10 cells.. but hear all cells are not showing.. how to show all cells please do help me.. i got stuck here from long

enter image description here

Error with type definitions using styled-components

Posted: 08 Aug 2021 08:09 AM PDT

I'm using styled-components in a react native project. I'm using typescript too, I installed the package and also installed the type definitions but this error is being displayed:

enter image description here

This is causing me an error as properties are not being returned. Does anyone have any idea how to solve?

Here below my package.json and my component.

"dependencies": {      "@react-navigation/native": "^6.0.2",      "@react-navigation/stack": "^6.0.2",      "expo": "~41.0.1",      "expo-splash-screen": "~0.10.2",      "expo-updates": "~0.5.4",      "react": "16.13.1",      "react-dom": "16.13.1",      "react-native": "~0.63.4",      "react-native-gesture-handler": "^1.10.3",      "react-native-reanimated": "~2.1.0",      "react-native-screens": "~3.0.0",      "react-native-unimodules": "~0.13.3",      "react-native-web": "~0.13.12",      "styled-components": "^5.3.0"    },    "devDependencies": {      "@babel/core": "^7.9.0",      "@types/react": "~16.9.35",      "@types/react-native": "~0.63.2",      "@types/styled-components": "^5.1.12",      "babel-preset-expo": "~8.3.0",      "jest-expo": "~41.0.0",      "typescript": "~4.0.0"    },  
import styled from 'styled-components/native';  import { RectButton } from 'react-native-gesture-handler';    export const Container = styled.View`    padding: 0 30px;  `;    export const SearchContent = styled.View`    width: 100%;    flex-direction: row;    align-items: center;  `;    export const Input = styled.TextInput`    width: 100%;    flex: 1;    height: 36px;    border: 1px solid #000;    border-bottom-left-radius: 5px;    border-top-left-radius: 5px;    padding: 12px;  `;    export const Button = styled(RectButton)`    background-color: #ff9000;      align-items: center;    justify-content: center;    width: 50px;    height: 36px;      border-top-right-radius: 5px;    border-bottom-right-radius: 5px;    `;  

Form submit sending POST request instead GET

Posted: 08 Aug 2021 08:11 AM PDT

I'm trying to make django-filter work, and it have worked, but now it suddenly have stopped.

The issue is that the submit button in the filter seems to be sending a POST request and not GET

Below is a snippet of the HTML code

<div class="form-group">      <form method="POST">        {% csrf_token %}        {{form|crispy}}        <button class="btn btn-outline-success" type="submit">Add product</button>  </div>      <div id="filter-menu">        <form method="get">          {{filter.form.nick_name|as_crispy_field}}          <br>          {{filter.form.domain|as_crispy_field}}          <br>          <button class="btn btn-outline-success" type="submit">Apply filter</button>        </form>  </div>  

I do have a POST-request submit button above as seen, and it seems like it's the one being triggerd, since when I debug the application, request.method == "POST" when pressing the apply filter button.

If needed, a snippet of my view is here (omitted messages and stuff)

def MyView(request):      user = request.user      user_products = MyModel.objects.filter(user=user).all()            ### Create filters ###      filter = get_user_filter_fields_wishlist(user_products) #Helper function for returning filters      filter = filter(request.GET,queryset = user_products)        if request.method == "POST":          post_form = MyForm(request.POST)              if post_form.is_valid():                           filter = get_user_filter_fields_wishlist(user_products)              filter = filter(request.GET,queryset = user_products)              form = MyForm()              context = {              "form":form,              "filter":filter              }                return render(request, "myapp/my_html.html",context=context)          else:              #invalid post_form              context = {                  "form":post_form,                  "filter":filter              }              return render(request, "myapp/my_html.html",context=context)              else: #Get request          form = MyForm()          context = {              "form":form,              "filter":filter          }                return render(request, "myapp/my_html.html",context=context)  

Map List<List<Integer>> in Java as List<Integer[]>

Posted: 08 Aug 2021 08:10 AM PDT

I have a nested List<List<Integer>> and Integer[] marks

When I am sending the request from Postman like this :

"numsList" : [      [1, 0],      [2, 2],      [2, 3]    ]  

everything is working fine. The request is getting mapped as numsList=[[1, 0], [2, 2], [2, 3]]

But when I am trying to write a junit, I am unable to create the request object in this format.

I am doing like this : var numsList = List.of(List.of(1,0,2,3,2,2)); and it is in the incorrect format.

Need some help to correct this.

How can I download 10 mb attachment from Exchange Server using Python

Posted: 08 Aug 2021 08:09 AM PDT

I am using this code but it downloads only kb attachment. After accessing to inbox I used below code:

for item in some_folder.all():      for attachment in item.attachments:          if isinstance(attachment, FileAttachment):              local_path = os.path.join(local_path, attachment.name)              with open(local_path, 'wb') as f:                  f.write(attachment.content)  

Appeal to the scrollbar

Posted: 08 Aug 2021 08:11 AM PDT

How to clean up unnecessary elements with BeautifulSoup?

Posted: 08 Aug 2021 08:11 AM PDT

I have multiple html files in directory and subfolders. I want to parse all html files within directory (recursively), find and remove from code target divs (with all content), plus all scripts and css. I want to remove all divs with id="wrapper", "header", "columnLeft", "adbox", "footer", plus all stylesheets and scripts. I tried regex, but this is not suitable for such tasks. I installed BS4 for Python 2.x, debian. What command could be used for this?

HTML file  

example.

Aggregates deduplication by property in Event Sourcing

Posted: 08 Aug 2021 08:10 AM PDT

I have the aggregate Product with properties: Id, ProductName, ProductPrice and events: ProductCreated, ProductNameChanged, ProductPriceChanged with commands.

I store my events in EventStore and I'm building the actual aggregate state before execute any command, in addition I have the async read model for this aggregate.

How I can check new product name, that my database has not other product with same name (in CreateProductCommand or ChangeProductName) ?

I can't use my read model, because it is async and I can't read all events for this aggregate type and build actual models for each product because this operation is expensive.

Making sense of date-time and datatypes in SQLite

Posted: 08 Aug 2021 08:11 AM PDT

I'm learning SQL and SQLite at the moment, and from what I understand, SQLite doesn't support a datetime datatype.

However, when I run the command PRAGMA table_info(Orders); it's showing one column as being of type datetime.

I've read that In SQLite, the datatype of a value is associated with the value itself, not with its container. taken from here https://www.sqlite.org/datatype3.html

I'm trying to understand what exactly this means, which may help to explain.

Can someone help me understand what's going on here?

enter image description here

Retry http request with backoff - (Nestjs - axios - rxjs) throws socket hang up

Posted: 08 Aug 2021 08:10 AM PDT

[second-Update]: i solved the issue by implmentig retry with promises and try & catch

[first-Update]: I tried the retrial mechanism with HTTP request with content-type: application/json and it works!! but my issue Is with content type form-data. I guess it's similar to this problem: Axios interceptor to retry sending FormData

Services architecture

I'm trying to make an HTTP request to service-a from NestJS-app. and I want to implement retry with backoff logic. to re-produce service-a failure, I'm restarting its docker container and make the HTTP request. retry logic implemented as 3 retries. first time as service-a is restarting.. throws 405 service not available error and make retry. all 3 retries failed with a socket hang up error.

HTTP request code using axios nestjs wrapper lib retryWithBackOff rxjs operator implementation

the first call throws a 405 Service Unavailable error. then application starts retries. first retry fires after service-a started, failed with error socket hang up first, second, and third retries failed with socket hang up. 3 sockets hang up errors

my expected behavior is: when service-a started then the first retry fires, it should work with a successful response.

notice that 3 retries don't log to the Nginx server anything!

How to pass a variable to Laravel Echo's presence channel to be available to its 'here' method?

Posted: 08 Aug 2021 08:10 AM PDT

My video app uses Laravel's Echo in its Vue.js frontend to listen to a presence channel to get online users through its .here method which returns user model of online users, and is working perfectly fine. What I am trying to do now is to pass another variable from a different model ($session->id) to be available to the 'here' Echo method as well.

So I created this channel class with the Session model bound to it alongside User model:

namespace App\Broadcasting;    use App\User;  use App\Session;    class lobbyChannel  {      /**       * Create a new channel instance.       *       * @return void       */      public function __construct()      {          //      }        /**       * Authenticate the user's access to the channel.       *       * @param  \App\User  $user       * @return array|bool       */      public function join(User $user, Session $session)      {            return [ 'id' => $user->id, 'name' => $user->name, 'sessionId' => $session->id ];                }  }  

Now I was trying to figure out where to feed that model a specific $session. First I thought I would do this in the backend as such:

$session = Session::find($id);  event(new userJoining($session));  

The problem is: this is a presence channel that is used only in the frontend, meaning that I never boradcast an event in the backend in the first place. The presence channel is only used in the frontend to show online users.

So I thought I could do this in Laravel's Echo in the frontend by adding a second parameter after the channel name:

Echo.join('lobby' + this.clinic.id, this.session)  

But this threw a 500 error.

How can I achieve what I am trying to do?

Why !strcmp is used instead of strcmp?

Posted: 08 Aug 2021 08:11 AM PDT

Here I wrote a code to find out whether a word is available or not.

#include <stdio.h>  #include <string.h>    char *names[] = {"Sushant", "Jhon", "Robin", "Mark", NULL};  int search(char *p[], char *names);  int main(void){      if(search(names, "Sushant") != -1){          printf("Sushant is in this list");      } else{          printf("Sushant is not in this list.");      }      return 0;  }    int search(char *p[], char *name){      register int t;      for(t = 0; p[t]; t++){          if(!strcmp(p[t], name)){              return t;          } else{              return -1;          }      }  }  

The code is working fine. But the problem is that. Why it is working? I am using strcmp to compare the array and given name but I am also using ! at the beginning of strcmp to reverse the statement. The thing is that there should be only strcmp instead of !strcmp can you please tell me why !strcmp is used here?

Three.js - Images managing - Recommendations

Posted: 08 Aug 2021 08:10 AM PDT

I have a project which looks actually like this:

enter image description here

The idea is: a generic room which increases its height, depending on the number of pictures the user loads.

It works... but as I load more than 100 pictures, it starts to hit performance pretty badly. This is my very first Three.js project, so I'm definitely a newbie.

I've been searching for some tips & tricks about optimization and I would like to have your opinion.

In order to respect the images dimensions, I do a Promise.all to fetch all images before the World initialization. Then I'm building the mesh according to the image width/height ratio with a PlaneBufferGeometry.

enter image description here

Apparently, it is recommended to load textures with power of two size (https://discoverthreejs.com/tips-and-tricks/ -> Textures part). Should I resize all my images so that their width & height are powers of two and the ratio is the closest to the original? How would you manage such a thing since the original images have many different sizes?

EDIT: This how is create the drawing object :

export class Drawing {      constructor(texture) {                            const imgW = Math.floor(texture.image.naturalWidth / 20);          const imgH = Math.floor(texture.image.naturalHeight / 20);                  const material = new MeshBasicMaterial({              color: 0xffffff,              map: texture          });                material.color.convertSRGBToLinear();            this.mesh = new Mesh(new PlaneBufferGeometry(imgW, imgH), material);      }  

In the end, I just the mesh to the scene.

ESP32 - analog Reading not working when using Webserver library

Posted: 08 Aug 2021 08:11 AM PDT

I tried to adapt a script for a webserver for my needs(All in Arduino IDE), but came across a strange problem, which I can't figure out. On Pin 4 I have connected a humidity Sensor, which works fine with this simple script

void setup() {    Serial.begin(9600);    pinMode(4, INPUT);  }  void loop() {    Serial.println(analogRead(4));    delay(500);  }  

Works perfectly. Though when I use this in the other script I always get the value 0 printed out. The datasheet says that the esp32 WROOM's Pin 4 is used as GPIO, ADC, HSPI_HD and Touch_0, but I don't think that anything else interferes in this code. Could you help me find the mistake ?

#include <WiFi.h>  #include <WiFiClient.h>  #include <WebServer.h>  //https://github.com/bbx10/WebServer_tng  //#include "Adafruit_BME280.h" //https://github.com/Takatsuki0204/BME280-I2C-ESP32    WebServer server ( 80 );    const char* ssid     = "xxx";  const char* password = "xxx";  #define ALTITUDE 216.0 // Altitude in Sparta, Greece    #define I2C_SDA 27  #define I2C_SCL 26  #define BME280_ADDRESS 0x76  //If the sensor does not work, try the 0x77 address as well  int LEDPIN = 32;    float temperature = 25.0;  float humidity = 95.0;  float pressure = 1023.0;    String  ledState = "OFF";    //Adafruit_BME280 bme(I2C_SDA, I2C_SCL);    void setup()   {    pinMode(LEDPIN, OUTPUT);    pinMode(4, INPUT);        Serial.begin(9600);          connectToWifi();      beginServer();  }    void loop() {      server.handleClient();      getTemperature();   getHumidity();   getPressure();   delay(1000);     }    void connectToWifi()  {    WiFi.enableSTA(true);        delay(2000);      WiFi.begin(ssid, password);        while (WiFi.status() != WL_CONNECTED) {          delay(500);          Serial.print(".");      }    Serial.println("");    Serial.println("WiFi connected");    Serial.println("IP address: ");    Serial.println(WiFi.localIP());  }    void beginServer()  {    server.on ( "/", handleRoot );    server.begin();    Serial.println ( "HTTP server started" );  }    void handleRoot(){     if ( server.hasArg("LED") ) {      handleSubmit();    } else {      server.send ( 200, "text/html", getPage() );    }    }      float getTemperature()  {    temperature = 25.0;  }    float getHumidity()  {    //humidity = 95.0;    int hum = analogRead(4);    Serial.println(hum);    humidity = float(hum);    //humidity = float(analogRead(4));    //Serial.println(analogRead(4));      }    float getPressure()  {    pressure = 1023.0;  }    void handleSubmit() {      String LEDValue;    LEDValue = server.arg("LED");    Serial.println("Set GPIO ");     Serial.print(LEDValue);        if ( LEDValue == "1" ) {      digitalWrite(LEDPIN, HIGH);      ledState = "On";      server.send ( 200, "text/html", getPage() );    }    else if( LEDValue == "0" )     {      digitalWrite(LEDPIN, LOW);      ledState = "Off";      server.send ( 200, "text/html", getPage() );    } else     {      Serial.println("Error Led Value");    }  }    String getPage(){    String page = "<html lang=en-EN><head><meta http-equiv='refresh' content='60'/>";    page += "<title>ESP32 WebServer - educ8s.tv</title>";    page += "<style> body { background-color: #fffff; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }</style>";    page += "</head><body><h1>Nicos Testserver</h1>";    page += "<h3>BME280 Sensor</h3>";    page += "<ul><li>Temperature: ";    page += temperature;    page += "&deg;C</li>";    page += "<li>Humidity: ";    page += humidity;    page += "%</li>";    page += "<li>Barometric Pressure: ";    page += pressure;    page += " hPa</li></ul>";    page += "<h3>GPIO 34</h3>";    page += "<form action='/' method='POST'>";    page += "<ul><li>LED";    page += "";    page += "<INPUT type='radio' name='LED' value='1'>An";    page += "<INPUT type='radio' name='LED' value='0'>Aus</li></ul>";    page += "<INPUT type='submit' value='Submit'>";      page += "</body></html>";    Serial.println(page);    return page;  }  

Annotate some scatter plot observations

Posted: 08 Aug 2021 08:11 AM PDT

I have made a dumbbell plot in matplotlib using the below "example dataframe" (df) and code.

The result looks pretty good but I am unable thus far to annotate the dumb-bell plots with their average values in df["avg"] column.

enter image description here

Can somebody guide me how to add the average values for each observation above their respective red dots? Thank you much!

Code follows below:

#example data  data = {'Brand': ['HC','TC','FF','AA'],  '2019Price': [22000,25000,27000,35000],  '2020Price':[25000, 30000, 29000, 39000]}  df = pd.DataFrame(data)  df["avg"] = (df['2019Price'] + df[ '2020Price'])/2  df = df.sort_values("2020Price", ascending = False)    #dumb bell plot  plt.hlines(y = df["Brand"], xmin = df["2019Price"], xmax =   df["2020Price"], color = "grey", alpha = 0.4)  plt.scatter(y = df["Brand"], x = df["2019Price"], color = "blue",   label = "2019")  plt.scatter(y = df["Brand"], x = df["2020Price"], color = "blue",   label = "2020")  plt.scatter(y = df["Brand"], x = df["avg"], color = "red", label =   "average")    plt.legend()  

HTML Purifier: How to prevent from removing href attribute of anchor tags

Posted: 08 Aug 2021 08:12 AM PDT

I am stuck in the HTML Purifier configuration to not removed any href attribute of anchor tags.

Current output:

enter image description here

Expected output: (with href attr)

enter image description here

Below is my HTML Purifier function:

    function html_purify($content)  {      if (hooks()->apply_filters('html_purify_content', true) === false) {          return $content;      }        $CI = &get_instance();      $CI->load->config('migration');        $config = HTMLPurifier_HTML5Config::create(          HTMLPurifier_HTML5Config::createDefault()      );        $config->set('HTML.DefinitionID', 'CustomHTML5');      $config->set('HTML.DefinitionRev', $CI->config->item('migration_version'));        // Disables cache     // $config->set('Cache.DefinitionImpl', null);        $config->set('HTML.SafeIframe', true);      $config->set('Attr.AllowedFrameTargets', ['_blank']);      $config->set('Core.EscapeNonASCIICharacters', true);      $config->set('CSS.AllowTricky', true);        // These config option disables the pixel checks and allows      // specifiy e.q. widht="auto" or height="auto" for example on images      $config->set('HTML.MaxImgLength', null);      $config->set('CSS.MaxImgLength', null);        //Customize - Allow image data      $config->set('URI.AllowedSchemes', array('data' => true));        //allow YouTube and Vimeo      $regex = hooks()->apply_filters('html_purify_safe_iframe_regexp', '%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/|player\.vimeo\.com/video/)%');        $config->set('URI.SafeIframeRegexp', $regex);      hooks()->apply_filters('html_purifier_config', $config);        $def = $config->maybeGetRawHTMLDefinition();        if ($def) {          $def->addAttribute('p', 'pagebreak', 'Text');          $def->addAttribute('div', 'align', 'Enum#left,right,center');          $def->addElement(              'iframe',              'Inline',              'Flow',              'Common',              [                  'src'                   => 'URI#embedded',                  'width'                 => 'Length',                  'height'                => 'Length',                  'name'                  => 'ID',                  'scrolling'             => 'Enum#yes,no,auto',                  'frameborder'           => 'Enum#0,1',                  'allow'                 => 'Text',                  'allowfullscreen'       => 'Bool',                  'webkitallowfullscreen' => 'Bool',                  'mozallowfullscreen'    => 'Bool',                  'longdesc'              => 'URI',                  'marginheight'          => 'Pixels',                  'marginwidth'           => 'Pixels',              ]          );      }        $purifier = new HTMLPurifier($config);        return $purifier->purify($content);  }  

What is the correct configuration to be added in order to allow href attr in any anchor tags?

onGoogleApiLoaded not rendering when state change

Posted: 08 Aug 2021 08:11 AM PDT

I have a <GoogleMapReact> component, and I render some circles on the map by a list of points, using onGoogleApiLoaded:

const tags = [allJobsTag].concat(settings.jobs.filter((job) => !job.deleted));  const [tag, setTag] = useState(allJobsTag);    function renderGeoFences(map, maps) {      _.map(geoFencesSites, (site) => {          let circle = new maps.Circle({              strokeColor: tag.id==='all-jobs'?"orange":'#1aba8b26',              strokeOpacity: 1,              strokeWeight: 4,              fillColor: '#1aba8b1f',              fillOpacity: 1,              map,              center: { lat: Number(site.location.latitude), lng: Number(site.location.longitude) },              radius: site.fenceSize,          });      });  }          let apiIsLoaded = (map, maps) => {      renderGeoFences(map, maps);  };    return(      <GoogleMapReact>          zoom={getMapZoom()}          center={{ lat: centerLatitude, lng: centerLongitude }}          options={{              fullscreenControl: false,              zoomControlOptions: { position: 3 },          }}          yesIWantToUseGoogleMapApiInternals          onGoogleApiLoaded={({ map, maps }) => apiIsLoaded(map, maps)}      >          {renderAddresses()}          {renderUsersLocation()}          {renderHighlightedUserRoute()}      </GoogleMapReact>  )  

and then rendering the circles in renderGeoFences.

However, this function is only called ones, and even though there are states in it, the circles would not be affected by the state. like in this example, when I try to change to color of the circles by the tag.id (tag is a state). How can I make this function render again when a state is changing?

How to set dynamic chunk size for a step with MutliResoucrItemReader?

Posted: 08 Aug 2021 08:10 AM PDT

I am using MultiResourceItemReader which takes the Resource Array. I want set the chunk size dynamically based on number of lines in each resource.

Below is the configured step in the configuration file.

@Bean  public Step processStep(){  return stepBuilderFactory.get("processStep").<itempojo,itempojo>chunk(3) //I dont want to set fixed chunk  here    .reader(multiResourceItemReader())    .processor(processor())    .writer(writer())    .listener(readerListener())    .build();    /** MulitResource Item Reader */    public MultiResourceItemReader<ItemPojo> multiResourceItemReader(){  MultiResourceItemReader<ItemPojo> itemreader = new   MultiResourceItemReader();  itemreader.setResources(resources);  itemreader.setDelegate(flatFileReader());  }   

Could any one suggest how can I approach dynamic chunk size, in the case of MultiResourceItemReader. please let me know incase any information required thankyou.

Anaconda Jupyter Notebook Kernel error ImportError: DLL load failed while importing win32api: The specified procedure could not be found

Posted: 08 Aug 2021 08:11 AM PDT

I had python 3.8 and jupyter notebook running in visual studio code before. After I installed Anaconda, I cannot run jupyter notebook any longer and am getting a Kernel error.

Traceback (most recent call last):    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\web.py", line 1704, in _execute      result = await result    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 769, in run  yielded = self.gen.throw(*exc_info)  # type: ignore    File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\handlers.py", line 69, in post  model = yield maybe_future(    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 762, in run  value = future.result()    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 769, in run  yielded = self.gen.throw(*exc_info)  # type: ignore    File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 98, in create_session  kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 762, in run  value = future.result()    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 769, in run  yielded = self.gen.throw(*exc_info)  # type: ignore    File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 110, in start_kernel_for_session  kernel_id = yield maybe_future(    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\tornado\gen.py", line 762, in run  value = future.result()    File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 176, in start_kernel  kernel_id = await maybe_future(self.pinned_superclass.start_kernel(self, **kwargs))    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_client\multikernelmanager.py", line 186, in start_kernel  km.start_kernel(**kwargs)    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_client\manager.py", line 337, in start_kernel  kernel_cmd, kw = self.pre_start_kernel(**kw)    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_client\manager.py", line 286, in pre_start_kernel  self.write_connection_file()    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_client\connect.py", line 466, in write_connection_file  self.connection_file, cfg = write_connection_file(self.connection_file,    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_client\connect.py", line 136, in write_connection_file  with secure_write(fname) as f:    File "C:\ProgramData\Anaconda3\lib\contextlib.py", line 113, in __enter__  return next(self.gen)    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_core\paths.py", line 461, in secure_write  win32_restrict_file_to_user(fname)    File "C:\Users\*****\AppData\Roaming\Python\Python38\site-packages\jupyter_core\paths.py", line 387, in win32_restrict_file_to_user  import win32api  ImportError: DLL load failed while importing win32api: The specified procedure could not be found.  

I have tried conda install ipykernel --update-deps and conda install pywin32 but the issue persists. How can I fix this?

In JavaScript, how can I have a function run at a specific time?

Posted: 08 Aug 2021 08:10 AM PDT

I have a website that hosts a dashboard: I can edit the JavaScript on the page and I currently have it refreshing every five seconds.

I am trying to now get a window.print() to run every day at 8 AM.

How could I do this?

No comments:

Post a Comment