python – Error setting the DATABASE_URL variable in the Windows PowerShell console

I have a problem trying to use the SQLALCHEMY tool. I am doing a course where it shows this code to display the list of a database called lecture3:

import os

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))

def main():
     flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
     for flight in flights:
          print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes!")


if __name__ == "__main__":
     main()

What the console throws at me:

Traceback (most recent call last):
  File "list.py", line 8, in 
    engine = create_engine(os.getenv("DATABASE_URL"))
  File "C:UsersDellAppDataLocalProgramsPythonPython38-32libsite-packagessqlalchemyengine__init__.py", line 479, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:UsersDellAppDataLocalProgramsPythonPython38-32libsite-packagessqlalchemyenginestrategies.py", line 56, in create
    plugins = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'

From what I was trying to find the solution to, one problem (and I think it would be the only one) is the variable DATABASE_URL, which is not defined. I do

echo $ DATABASE_URL

in the PowerShell console and it does not display anything, it goes directly to the other command line. I tried to adjust it with SET and EXPORT:

SET DATABASE_URL = "postgresql: // myCreatedUser: myPassword @ localhost: 5432 / lecture3"

but when I echo again, it doesn't show anything.

(Another clarification is that I don't know if what I tried to adjust is correct, I think so, but also the echo doesn't show anything, so I have no way of check it)

Likewise, I also tried to replace what I tried to define in the create_engine

engine = create_engine ("postgresql: // myCreatedUser: myPassword @ localhost: 5432 / lecture3")

but it doesn't matter either.

I tried to be as explanatory as possible. I hope this is enough. I am new to using Postgresql with Python. Before that, I searched everywhere but I couldn't find a solution, so I use it as a last resort.

Greetings and thanks!

error handling – What should I send as an answer for asp.net core 3.1 web api with ef core 3.0 and the repository model

What I'm asking is that what is the right way to return data from a controller
implementation of the repository model. Here is the code for my controller –

using Demo.Repository;
using Demo.Models.Dtos;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;


namespace Demo.Controllers
{
    (Route("api/roles"))
    (ApiController)
    (Authorize)
    (EnableCors("CorsPolicy"))

public class RolesController : ControllerBase
{
    private readonly IRoleRepository _rolesRepo;

    public RolesController(IRoleRepository rolesRepo)
    {
        _rolesRepo = rolesRepo;
    }


    (HttpGet)
    public IActionResult Get((FromQuery)PageDto pageDto)
    {
        var result = _rolesRepo.GetRoles(pageDto.PageNo, pageDto.PageSize).Result;
        return Ok(result);
    }


    (HttpPost("create"))
    public IActionResult Post(RoleDto rolesDto)
    {
        var result = _rolesRepo.CreateRole(rolesDto).Result;
        return result;
    }


    (HttpPut)
    public IActionResult Put(RoleDto roleDto)
    {
        var response = _rolesRepo.EditRole(roleDto).Result;
        return response;
    }


    (HttpPost("delete"))
    public IActionResult Delete(RoleDto roleDto)
    {
        var result = _rolesRepo.DeleteRole(roleDto).Result;
        return result;
    }
    }
}

and this is the repository interface –

using Demo.Models;
using Demo.Models.Dtos;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace Demo.Repository
{
    public interface IRoleRepository
    {
        Task> GetRoles(int pageNo, int pageSize);

        Task CreateRole(RoleDto roleDto);

        Task EditRole(RoleDto roleDto);

        Task DeleteRole(RoleDto roleDto);
    }
}

and that’s the implementation of the repository –

using Demo.Models;
using Demo.Repository;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using AutoMapper;
using Demo.Models.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Linq;

namespace Data.Data
{
    public class RolesData : IRoleRepository
    {
        private readonly DemoContext _db;
        private readonly IMapper _mapper;

        public RolesData(DemoContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
        }


        public async Task CreateRole(RoleDto roleDto)
        {
            try
            {
                var roles = _mapper.Map(roleDto);
                await _db.AddAsync(roles);
                var result = await _db.SaveChangesAsync();

                if (result > 0)
                    return new StatusCodeResult(StatusCodes.Status201Created);
                else
                    return new StatusCodeResult(StatusCodes.Status400BadRequest);
            }
            catch (Exception e)
            {
                //To Do LogException(e);
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }


        public async Task DeleteRole(RoleDto roleDto)
        {
            try
            {
                var role = _mapper.Map(roleDto);

                _db.Remove(role);
                var result = await _db.SaveChangesAsync();

                if (result > 0)
                    return new StatusCodeResult(StatusCodes.Status201Created);
                else
                    return new StatusCodeResult(StatusCodes.Status400BadRequest);
            }
            catch (Exception e)
            {
                //To Do LogException(e);
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }
        }


        public async Task EditRole(RoleDto roleDto)
        {
            try
            {
                var role = _mapper.Map(roleDto);

                _db.Entry(role).State = EntityState.Modified;
                var result = await _db.SaveChangesAsync();

                if (result > 0)
                    return new StatusCodeResult(StatusCodes.Status200OK);
                else
                    return new StatusCodeResult(StatusCodes.Status400BadRequest);
            }
            catch (Exception)
            {
                return new StatusCodeResult(StatusCodes.Status500InternalServerError);
                //throw;
            }
        }


        public async Task> GetRoles(int pageNo, int pageSize)
        {
            PagedResult roleList = new PagedResult();
            List roles = new List();
            Pagination pagination = new Pagination();

            try
            {
                var query = _db.Roles;
                var result = await query.Skip((pageNo - 1) * pageSize).Take(pageSize).ToListAsync();
                result = result.OrderBy(x=>x.Id).ToList();
                var count = query.Count();

                pagination.RowCount = query.Count();
                pagination.CurrentPage = pageNo;

                pagination.PageCount = (int)Math.Ceiling(count / (float)pageSize);
                pagination.PageSize = pageSize;

                roles = _mapper.Map>(result);

                roleList.Results = roles;
                roleList.Pagination = pagination;

                return roleList;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

As you can see, I am returning an http status code from my repository, indicating the success or failure of the data operation and returning the same status code to from the controller.

it works, but i don't think that's the best way to do it. First, I want my repository class to be strictly data bound, but to return the status code, I have to use Microsoft.AspNetCore.Http which, I think, should not belong to this class. Now I can do it instead –

public async Task CreateRole(RolesDto rolesDto)
        {
            try
            {
                var roles = _mapper.Map(rolesDto);
                await _db.AddAsync(roles);
                int result = await _db.SaveChangesAsync();

                if (result > 0)
                {
                     //return success or something
                }
            }
            catch(Exception)
            {
                //To Do LogException(e);
                throw;
            }
        }

but what should i return on exception and not only here but also in the controller. I tried this in my controller –

(HttpPost("create"))
        public IActionResult Post(RolesDto rolesDto)
        {
            try
            {
                if (!ModelState.IsValid)
                    return BadRequest(ModelState);

                var result = _rolesRepo.CreateRole(rolesDto).Result;

                if (result == "success")
                    return Ok(result);

                else
                    return NotFound("No data found");

            }
            catch (Exception e)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
            }
        }

which looks great but what should I return on exception in my repo class. Either am I doing everything right (I mean the recommended way) or do I have to change something.

Note – I know I can create middleware to handle exceptions and I did, but that is not what I am asking.

r – Save_kable error when exporting an image

I am working with the kableExtra package in RStudio designed to create tables and I have problems during export. I enclose examples of the manual that the creator himself downloaded.

To export a simple table like the following, I have no problem.

kable(mtcars, "latex", booktabs = T) %>%
  kable_styling(latex_options = c("striped", "scale_down")) %>%
  row_spec(1, color = "red") %>%
  as_image(width = 8)

However, if I go into manipulating the aesthetics of tables like the following code would be:

iris(1:10, ) %>%
  mutate_if(is.numeric, function(x) {
    cell_spec(x, bold = T, 
              color = spec_color(x, end = 0.9),
              font_size = spec_font_size(x))
  }) %>%
  mutate(Species = cell_spec(
    Species, color = "white", bold = T,
    background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
  )) %>%
  kable(escape = F, align = "c") %>%
  kable_styling(c("striped", "condensed"), full_width = F)  %>%
  as_image() 

I get the following:

Error in setwd(dir) : no es posible cambiar el directorio de trabajo
Además: Warning messages:
1: In file.create(file_temp_html) :
  cannot create file '.C:UsersxxxxAppDataLocalTempRtmpYB5Qi9file21305d2467c82130611b6397.html', reason 'Invalid argument'
2: In normalizePath(path.expand(path), winslash, mustWork) :
  path(1)=".C:UsersxxxxxAppDataLocalTempRtmpYB5Qi9file21305d2467c82130611b6397.html": El nombre de archivo, el nombre de directorio o la sintaxis de la etiqueta del volumen no son correctos

However, if I delete the last line, the one in charge of exporting the image, I can perfectly see the table in the RStudio session. That is, when running the following code, I have no problem:

iris(1:10, ) %>%
  mutate_if(is.numeric, function(x) {
    cell_spec(x, bold = T, 
              color = spec_color(x, end = 0.9),
              font_size = spec_font_size(x))
  }) %>%
  mutate(Species = cell_spec(
    Species, color = "white", bold = T,
    background = spec_color(1:10, end = 0.9, option = "A", direction = -1)
  )) %>%
  kable(escape = F, align = "c") %>%
  kable_styling(c("striped", "condensed"), full_width = F) 

I have tried different modes but I can't find the solution and I don't know what can go wrong.

java – SpringBoot JPA Repository – getting selected fields displays "Column not found" error

I want retrieve the selected columns, preferably dynamically.

For now, I'm specifying static columns – id, title, description.

Category.java

@Entity(name="Category")
@Table(name="categories")
public class Category {

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private long id;
   private String slug;
   private String title;
   private String description;
   private String preview_image;
   private int isFeatured;

   /*  Getters, setters etc */
}

CategoryRepository.java

public interface CategoryRepository extends JpaRepository {

    @Query(
        value = "SELECT id, title, description FROM categories", 
        nativeQuery = true
    )
    List findAll();
}

This gives the error:

The column & # 39; is_featured & # 39; is not found. Exception class: class
org.springframework.dao.InvalidDataAccessResourceUsageException
Exception (cannot execute query; SQL (SELECT id, title, description)
DE categories); the nested exception is
org.hibernate.exception.SQLGrammarException: unable to execute query)

Any idea how this error can be resolved? I was thinking of using another model instead of Category but I have to make the fields dynamic later. It is difficult to create a model class if I do not know which fields to return.

Besides, is there a way to do this @Query dynamic code as it returns the columns mentioned in the parameter?

Any help would be appreciated. Thanks in advance! 🙂

7 – General error: 1366 Invalid integer value when downloading the image

I am using Drupal 7 and I had the following error while uploading the image.

DOException: SQLSTATE (HY000): General error: 1366 Invalid integer value: & # 39; & # 39; for the column & # 39; field_third_section_image_width & # 39; at line 1:

INSERT INTO {field_data_field_third_section_image} (entity_type, entity_id, revision_id, bundle, delta, language, field_third_section_image_fid, field_third_section_image_alt, field_third_section_image_title, field_third_section_image_width, 
field_third_section_image_height) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4,
 :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7,
 :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10);
     Array ( (:db_insert_placeholder_0) => node 
    (:db_insert_placeholder_1) => 107 
    (:db_insert_placeholder_2) => 107 
    (:db_insert_placeholder_3) => page 
    (:db_insert_placeholder_4) => 0 
    (:db_insert_placeholder_5) => und 
    (:db_insert_placeholder_6) => 12464 
    (:db_insert_placeholder_7) => 
    (:db_insert_placeholder_8) => 
    (:db_insert_placeholder_9) => 
    (:db_insert_placeholder_10) => ) 

    in field_sql_storage_field_storage_write() (line 514 of /mysite/modules/field/modules/field_sql_storage/field_sql_storage.module).

This also gives an error related to the image on recent newspapers

Unable to generate derived image located on public: //styles/thumbnail/public/imac1.png.

Whenever I try to download the image and save the node, it gives the following error.
I have already given write permission to the file directory and to the tmp directory.

An idea?

magento2 – How to go to the checkout section of the cashier and throw an error in Magento 2?

In my checkout_type_onepage_save_order observer, I have a code to do a validation and this will make the customer go to the checkout and will throw an error, in Magento 1.9 I can do it like this:

Mage::getSingleton('checkout/type_onepage')->getCheckout()->setGotoSection('review');
throw new Mage_Core_Exception($helper->__('There was an error processing your order. Please read error message or contact us ajk.com'));

How can I do something similar like this in Magento 2.3.4?

8 – Unexpected error when deleting the taxonomy

By deleting a whole term or vocabulary, I get this error:

The website encountered an unexpected error. Please try again later.

I have tried to delete terms but this error has occurred but these have been deleted successfully.

In the error log, I see this error:

 (Tue Apr 07 18:27:20.141012 2020) (proxy_fcgi:error) (pid 24707:tid 140522664453888) (client 103.87.207.242:59315) AH01071: Got error 'PHP message: Error: Call to a member function delete() on null in govtschemes.in/modules/taxonomy_breadcrumb/taxonomy_breadcrumb.module

 on line 110 #0 (internal function): 
taxonomy_breadcrumb_taxonomy_vocabulary_delete(Object(Drupal\taxonomy\Entity\Vocabulary))n#1 govtschemes.in/core/lib/Drupal/Core/Extension/ModuleHandler.php(403): call_user_func_array('taxonomy_breadc...', Array)n#2 govtschemes.in/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(347): Drupal\Core\Extension\ModuleHandler->invokeAll('taxonomy_vocabu...', Array)n#3 

govtschemes.in/core/lib/Drupal/Core/Entity/EntityStorageBase.php(434): Drupal\Core\Config\Entity\ConfigEntityStorage->invokeHook('delete', Object(Drupal\taxonomy\Entity\Vocabulary))n#4 govtschemes.in/core/lib/Drupal/Core/Entity/EntityBase.php(403): 

Drupal\Core\Entity\EntityStorageBase->delete(Array)n#5 govtschemes.in/core/lib/Drupal/Core/Entity/EntityDeleteFormTrait.php(122): Drupal\Cor...n', referer: http://www.govtschemes.in/admin/structure/taxonomy/manage/govt_department/delete?destination=/admin/structure/taxonomy

error 10054 sql server 2014

enter description of image here

When I open the SQL server, I got error 10054. Recently, I changed the name of the server and I have probably been having this problem ever since. How can I fix it?

Chrome developer tools error

I was using the chrome dev debugging tool for my javascript code, but when I switched to the sources tab, I couldn't display my code, but the console shows the output correct, how to fix this problem as soon as possible?

Error exporting inference graph: tensorflow.python.framework.errors_impl.NotFoundError

I have successfully trained my model, but I am trying to export the inference graph, it shows the error below. What is the solution to the error below

Traceback (most recent call last):
File "export_inference_graph.py", line 162, in 
tf.app.run()
File "C:Users8470pAnaconda3envsObjectDeclibsite- 
packagestensorflow_corepythonplatformapp.py", line 40, in run
_run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
File "C:Users8470pAnaconda3envsObjectDeclibsite-packagesabslapp.py", line 299, in run
_run_main(main, args)
File "C:Users8470pAnaconda3envsObjectDeclibsite-packagesabslapp.py", line 250, in _run_main
sys.exit(main(argv))
File "export_inference_graph.py", line 146, in main
text_format.Merge(f.read(), pipeline_config)
File "C:Users8470pAnaconda3envsObjectDeclibsite- 
packagestensorflow_corepythonlibiofile_io.py", line 122, in read
self._preread_check()
File "C:Users8470pAnaconda3envsObjectDeclibsite- 
packagestensorflow_corepythonlibiofile_io.py", line 84, in _preread_check
compat.as_bytes(self.__name), 1024 * 512)
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: 
training/faster_rcnn_inception_v2_pets.config : The system cannot find the file specified.
; No such file or directory`