Code Bug Fix: How to implement search in a cell editor implementing column of ag grid?

Original Source Link

I am using a Cell editor in a column like below
columnDefs = [
{
field: ‘name’,
width: 300,
editable: true,
cellEditor: ‘agSelectCellEditor’,
cellEditorParams: {
values: [
‘Bob’,
‘Harry’,
‘Sally’,
}]
Here the cell editor has only 3 values.What if there are 100 values.Is it possible to implement a search field in the dropdown.If so how?
Thanks.

Tagged : / /

Code Bug Fix: Matplotlib polar plots: How to print both angles and labels?

Original Source Link

I am trying to plot a polar plot with using the following.
The problem is that when we put labels for different theta values, the value of theta is no more visible. For example at 90 degree if I want to put a label, say A, then only A is visible but not 90 degrees. I would like both of them to appear. How can I do that?

ax1 = fig.add_subplot(111, projection='polar')
c = ax1.scatter(df['P_radian'], abs(df['radius']), c=df['P_type'])
theta_range = range(0, 360, 45);
theta_label = (r'A_alpha', r'B_alpha', r'A_beta', r'B_beta', r'A_gamma', r'B_gamma', r'A_delta', r'B_delta')
lines, labels = ax1.set_thetagrids(theta_range, theta_label )

So in this case, when I want to print theta_labels, it doesn’t show the corresponding values of theta ticks. If I remove theta_label, it shows the tick values.
Is there anyway with which I get to print both the angle and the label without manually modifying theta_label values?

Tagged : / /

Code Bug Fix: Why do I get a run error from Aptana on Ubuntu 20.04

Original Source Link

I’ve installed Aptana Studio 3 and Java 11 on Ubuntu 20.04. When I run it I get as far as the workplace dialog and it then crashes. The error log has numerous references to eclipse, such as:

!ENTRY org.eclipse.osgi 4 0 2020-05-14 20:08:37.125 !MESSAGE
Application error !STACK 1 org.eclipse.e4.core.di.InjectionException:
java.lang.NoClassDefFoundError: javax/annotation/PostConstruct at
org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:410)
at
org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:318)
at
org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162)
at
org.eclipse.e4.ui.internal.workbench.swt.E4Application.createDefaultHeadlessContext(E4Application.java:491)

and many similar lines.

What am I doing wrong?

John

I’ve found the answer. Aptana won’t work with Java 11. I replaced that with Java 8 and all is well.

Tagged : / /

Code Bug Fix: TypeError: ‘str’ object does not support item assignment, pandas operation

Original Source Link

I am trying to grab some finanical data off a financial website. I wanna manipulate df['__this value__']. I did some research myself, and I understand the error fine, but I really have no idea how to fix it. This is how my code is like:

import requests
import bs4
import os
import pandas as pd


def worker_names(code=600110):

    ......

    df = pd.DataFrame({'class': name_list})
    worker_years(df)


def worker_years(df, code=600110, years=None):

    if years is None:
        years = ['2019', '2018', '2017', '2016']
        url = 'http://quotes.money.163.com/f10/dbfx_'
              + str(code) + '.html?date='
              + str(years) + '-12-31,'
              + str(years) + '-09-30#01c08'

        ......

        df['{}-12-31'.format(years)] = number_list  # this is where the problem is
        df = df.drop_duplicates(subset=['class'], keep=False)
        df.to_csv(".\__fundamentals__\{:0>6}.csv".format(code),
                  index=False, encoding='GBK')
        print(df)

if __name__ == '__main__':
    pd.set_option('display.max_columns', None)
    pd.set_option('display.unicode.ambiguous_as_wide', True)
    pd.set_option('display.unicode.east_asian_width', True)

    fundamental_path = '.\__fundamentals__'
    stock_path = '.\__stock__'

    worker_names(code=600110)

Is there any ways that I can work around? please help! THX ALL!
PS for full codes, I provided in answer section. sorry for the inconviniences.

your codes df['{}-12-31'.format(years)] = number_list demostrate a very good example of you can't make 2 variables on both side of the equation. Try this:

df_year = pd.DataFrame({'{}'.format(year): number_list})
df = pd.concat([df, df_year], axis=1)

work around with dataframe, there are many different ways to get the same result.

import requests
import bs4
import os
import pandas as pd


def worker_names(code):

    url = 'http://quotes.money.163.com/f10/dbfx_'
          + str(code) + '.html?date=2019-12-31,2019-09-30#01c08'


    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
    }

    response = requests.get(url, headers=headers).content
    soup = bs4.BeautifulSoup(response, 'html5lib')

    DuPond_name = soup.find_all(name='td', attrs={'class': 'dbbg01'})

    name_list = []
    for i, names in enumerate(DuPond_name, 1):
        name = names.getText()
        name_list.append(name)

    df = pd.DataFrame({'class': name_list})
    worker_years(code, df)

def worker_years(df, code, years=None):

    if years is None:
        years = ['2019', '2018', '2017', '2016']
        url = 'http://quotes.money.163.com/f10/dbfx_'
              + str(code) + '.html?date='
              + str(years) + '-12-31,'
              + str(years) + '-09-30#01c08'


        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
        }

        response = requests.get(url, headers=headers).content
        soup = bs4.BeautifulSoup(response, 'html5lib')

        DuPond_number = soup.find_all(name='td', attrs={'class': 'dbbg02'})

        number_list = []
        for i, numbers in enumerate(DuPond_number, 1):
            number = numbers.getText()
            number_list.append(number)
            # print(number_list)

        df['{}-12-31'.format(years)] = number_list  # this is where the problem is
        df = df.drop_duplicates(subset=['class'], keep=False)
        df.to_csv(".\__fundamentals__\{:0>6}.csv".format(code),
                  index=False, encoding='GBK')
        print(df)


if __name__ == '__main__':
    pd.set_option('display.max_columns', None)
    pd.set_option('display.unicode.ambiguous_as_wide', True)
    pd.set_option('display.unicode.east_asian_width', True)

    for root, dirs, files in os.walk('.\__stock__'):
        for csv in files:
            if csv.endswith('.csv'):
                path = csv
                prefix = os.path.splitext(path)
                print(prefix[0])
                worker_names(prefix[0])

Tagged : / / /

Code Bug Fix: Need help to fetch json data with Axios dependancy for react

Original Source Link

I need help using the axios dependancy on react.
I’m fetching data from this endpoint: https://api.covid19api.com/summary

I setup a config for my API (config.jsx)

import axios from 'axios';

export default axios.create({   
    baseURL: `https://api.covid19api.com/summary`,
    responseType: "json" 
});

then i call it in my App, (a class component) as API

import API from './config.jsx';

and execute it within my ComponentDidMount()

 componentDidMount() {
    API.get().then(res => {     
      const countries = JSON.stringify(res.data.Countries);
      //console.log(countries);
      this.setState({ covid: countries });
      console.log(`Etat du state:  ${this.state.covid}`);
    })
}

I get the data, store it in my state named ‘covid’, but when it comes to map over the results i get an error “TypeError Cannot read property ‘map’ of null” I think i have to convert the data into an array but i don’t know how to do this .

render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1>{this.state.appliname}</h1>

          {this.state.covid.map(item => (
            <div>{item.Country}</div>
          ))}

        </header>
      </div>
    );
  }

Here’s the full script on codesandbox: https://codesandbox.io/s/intelligent-faraday-ykewv?file=/src/App.js

Thanks

There are several things you need to consider:

  1. Always handle error in promises. Sometimes you may face API failure, so you should handle if the API request gets failed what we should do. So simply add a catch handler to your promise chain.

  2. You should always handle first data initiation. In the first render of your page, there is no this.state.covid so you can’t pass it to your view and map through it, so if you do this it will throw an error. To make this work you should add conditional rendering to your element.

  3. Define your first state initiation correctly. Since you expect your this.state.covid to be an array, so you should define it as an array in the first place (this.state = {covid: []}).

  4. Avoid passing strings to Array#map. When you try to convert your incoming items from API to JSON with JSON.stringify(res.data.Countries) it will make your data as JSON. Since JSON comes with string type it won’t fit array helpers like Array#map, when you got your data there is no need to make JSON of the. If in any case, your incoming data was JSON itself you should parse it with JSON.parse().

Working demo:

CodeSandbox

  1. Set init state default array

this.state = { covid: [], appliname: “CovidFacts” };

  1. Set countries
const countries = res.data.Countries;

Follow all :

import React from "react";
import "./App.css";
import API from "./config.jsx";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      covid: [],
      appliname: "CovidFacts"
    };
  }

  componentDidMount() {
    API.get().then(res => {
      const countries = res.data.Countries;
      this.setState({ covid: countries });
      console.log(`Etat du state:  ${this.state.covid}`);
    });
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1>{this.state.appliname}</h1>
          {this.state.covid.map(item => (
            <div>{item.Country}</div>
          ))}
        </header>
      </div>
    );
  }
}

export default App;

Tagged : /

Code Bug Fix: Objects: Value always undefined

Original Source Link

I am working on some keybinding functionality and came across something that is quite confusing to me.

I am doing some regex validation against the user defined keybinding pattern and would then like to assign the pattern as key and value to definedKeys:

const definedPattern = ['a', 'b']
let definedKeys = {}

const bindKeys = () => {
  const charKey = (String(definedPattern[0]) + String(definedPattern[1])).match(/^[a-zA-Z]{2}$/)
    
  if (charKey) {
    definedKeys[charKey.input[0]] = definedKeys[charKey.input[1]]
  }
  
  console.log(definedKeys)
}

bindKeys()

  • Use definedKeys instead of definedCharKeys as it is not declared neither initailized

  • Assigning value directly to key instead of refrencing value from definedKeys because value is not still set and it will be always undefined.

  definedKeys = {};
  const encodeKey = (pKey) => {
      charKey = (String(pKey[0]) + String(pKey[1])).match(/^[a-zA-Z]{2}$/);
      if (charKey) {
          // charKey.input = 'ab'
          definedKeys[charKey.input[0]] = charKey.input[1];
      }
  }

  encodeKey('ab');
  console.log(definedKeys);

Isn’t it because you don’t put anything in definedKeys but instead you put it in definedCharKeys?

As per the code. You are not assigning anything in “definedKeys”. You are assigning a value in “definedCharKeys” that’s why you are getting undefined for the “definedKeys”.

Please post full code where are you calling the function so that developers can provide you solution.

Tagged : /

Code Bug Fix: CSS span or p goes outside of div

Original Source Link

I am trying to replicate stackoverflow-like design and ran into problem.

<div class="flex-grow-0 pd-around-m">  # line 1
    <div class="flex-col fill-row mr-around-s"> # line 2
        <div class="flex-row fill-row"> # line 3
            <div class="flex-col justify-center mr-around-m"> # line 4
                //Buttons
            </div>
            <span>
                //Long Text!!
            </span>
        </div>
        <div class="answer-bottom"></div>
    </div>
</div>
.fill-row {
    width: 100%
}

.flex-col {
    display: flex;
    flex-direction: column;
}

.flex-row {
    display: flex;
    flex-direction: row;
}

.mr-around-m {
    margin: 1rem;
}

.justify-center {
    justify-content: center;
}

When I enter long text in <span>, <div> in line 2, line 3 goes out of div box in line 1.

I tried adding white-space: pre-line to div in line 2 and directly at span but still text goes out of the box.

How can I keep the text inside parent div?

enter image description here

navigation bar on the left has property width:20% but gets squashed. Is this because of the textbox problem I asked above?

EDIT
https://jsfiddle.net/pzcu2yjn/
Here’s a replication of my problem. if you make the text in span short enough, navbar and menu will have some empty space in the left maintaining 20% of the screen. however, if you leave the long text as it is, it gets squashed and 20% gets ignored

Few things:

  1. On using flex it is good to provide width for left and right container since container will not know what it should when content increases.
  2. Once you have the width assigned to the right container that is when you can use wrap functionality so the wrap works only for right container and it doesn’t have no impact on less container. overflow-break-word;

NOTE:

I have removed unwanted code from the code, you can put it back it has no impact if those are needed.

.flex-row {
  display: flex;
  width: 100%;
}

.navbar {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  border-right: 0.05rem solid var(--main-border-color);
  align-items: flex-end;
  width: 20%;
  border: 1px solid red;
}

.pd-around-m {
  width: 80%;
  border: 1px solid blue;
  display: inline-block;
  overflow-wrap: break-word;
}
<div class="flex-row">
  <div class="navbar">
    <div>
      menu1
    </div>
  </div>

  <div class="flex-grow-0 pd-around-m">
    <div class="flex-col fill-row mr-around-s">
      <div class="fill-row">
        <span>
                  AaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaa
                  </span>
      </div>
      <div class="answer-bottom"></div>
    </div>
  </div>

</div>

You can add overflow: hidden; to prevent the text from going outside of your div.

There’s a very similar question with a precise answer:
<span> element going outside of <div> element

Tagged : / /

Code Bug Fix: Is there an easy way to change timezone only on view laravel?

Original Source Link

So I already save any date on my database with UTC, and I can get it just like $data->created_at or $data->blocked_at. So in my config, I set timezone to UTC, then i want to convert when on view from UTC to UTC+7 or another timezone.

Is there an easy way to convert timezone i want when on view for all dates?

I’m still using Laravel 5.8

Edit:

I’m using the answer but implement that on my base model, like this:

public function getDateConverter($key){
    if(strtotime($this->{$key})){
        $date = Carbon::createFromFormat('Y-m-d H:i:s', $this->{$key});
        $date->setTimezone(env("APP_TIMEZONE_VIEW"));
        return $date->toDateTimeString();
    } else {
        return null;
    }
}

And I will call the column name like this $data->getDateConverter(“created_at”);

You can use Carbon which is included in the core

$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');

Europe/Stockholm is your default timezone and UTC is what you want to set

If you want to convert it from a model when displaying, try Accessors

public function getCreatedAtAttribute($value)
    {
        $date = Carbon::createFromFormat('Y-m-d H:i:s', $value, 'Europe/Stockholm');
        $date->setTimezone('UTC');
        return $date->toDateTimeString();
    }

well in case if you want to chnage your timezone when inserting the time then

Use 'timezone' => 'Asia/Kolkata'. in your config/app.php

By this you can set your applications default timezone..

Tagged : / /

Code Bug Fix: wp_update_user overwriting activation key

Original Source Link

I’m running into an issue with a frond end reservation system (NativeRentalSystem for car rentals) for wordpress, when the system creates a account for the user the activation link doesn’t work (when adding a user via the dashboard the code does work). After a bit of digging in the code of the Rental System i found that the function wp_update_user() seems to reset the activation code to null

the following code is ran by the system

$newWpUserId = register_new_user( $validEmail, $validEmail );

This seems to trigger sending the welcome email, right after the above code it runs the following snippet

wp_update_user( array(
    'ID'           => $newWpUserId,
    'display_name' => $validFirstName,
    'role'         => 'customer'
);

uncommenting this code the activation code works.

I tried grabbing the activation key using get_password_reset_key and then passing this as a parameter but this doesn’t work either

I’m also running a plugin to overwrite the welcome email when i disable it it still does not work

Any one know how to fix this ? perhaps an alternate way of stetting the role and display name ?

Tagged :

Code Bug Fix: R – compare two string variables and derive a third variable based on the comparison

Original Source Link

Let’s say you have a dataframe that looks like this:

Var1 Var2
A    A  
B    B  
A    B  
B    A 

I’m trying to make a variable Var3 that would be 1 if Var1 and Var2 are equal and 0 if they are not. So, the dataframe should look like this:

Var1 Var2 Var3
A    A    1
B    B    1
A    B    0
B    A    0

I’m using the following code:

data %<>%
  mutate_if(vars(Var1) == vars(Var2), Var3 = 1) %>% 
  mutate_if(vars(Var1) != vars(Var2), Var3 = 0)

However, I am getting the following error:

Error in vars(Var1) == vars(Var2) : 
  comparison of these types is not implemented

What am I supposed to do then?

With dplyr I would use case_when, its helpfull when you have multiple conditions.

df <- data.frame(Var1 = c("A","B","A","B"),
                 Var2 = c("A","B","B","A"))

df %>%
  mutate(Var3 = case_when(Var1 == Var2 ~ 1,
                          Var1 != Var2 ~ 0))

No need to make it too complicated you can directly do :

as.integer(df$Var1 == df$Var2)
#Or even shorter
#+(df$Var1 == df$Var2)
#[1] 1 1 0 0

which is faster way than doing with ifelse

ifelse(df$Var1 == df$Var2, 1, 0)

Tagged :