How do I undo resolve SMOTENN attribute error sm.fit.sample(x,y) AttributeError: 'function' object has no attribute 'sample' - smote

from imblearn.combine import SMOTEENN
sm = SMOTEENN()
X_resampled, y_resampled = sm.fit.sample(x,y)

Related

Getting an AttributeError using RetrieveUpdateDestroyAPIView

I am new to django and am using mongoengine. I am trying to create an employee database using DRF. All of the APIs are working well but whenever I am trying to fetch a single document which has been deleted its giving me an AttributeError at employee/<int:pk>.
This is my models.py file:-
from mongoengine import Document, SequenceField, StringField, IntField, EmailField from enum import Enum from rest_framework.exceptions import ValidationError
class GenderEnums(str, Enum):
MALE = "Male"
FEMALE = "Female"
OTHER = "Other"
#classmethod
def choices(cls):
return [item.value for item in cls]
models.py:-
class Employee(Document):
employee_id = SequenceField(required=False, primary_key=True)
name = StringField(required=True, max_length=50)
age = IntField(required=True, min_value=18, max_value=50)
company = StringField(required=True, max_length=50)
gender = StringField(choices=GenderEnums.choices(), default=GenderEnums.OTHER)
email = EmailField(required=True, unique=True)
password = StringField(required=True)
def clean(self):
if self.gender == GenderEnums.MALE.value and self.age > 30:
raise ValidationError("For male employees, age should be under 31")
elif self.gender == GenderEnums.FEMALE.value and self.age < 20:
raise ValidationError("For female employees, age should be above 20")
serializers.py:-
from rest_framework_mongoengine import serializers
from .models import Employee
class EmployeeSerializer(serializers.DocumentSerializer):
class Meta:
model = Employee
fields = "__all__"
views.py:-
from .serializers import EmployeeSerializer
from .models import Employee
from rest_framework.response import Response
from rest_framework_mongoengine import generics
import logging
from rest_framework.exceptions import ValidationError
from mongoengine import DoesNotExist
import time
logging.basicConfig(filename="logs.txt", filemode="a", level=logging.INFO)
# GeneralSerializer.Meta.model = Employee
# serializer_used = GeneralSerializer
class EmployeeAdd(generics.CreateAPIView):
try:
serializer_class = EmployeeSerializer
logging.info(f"Document created successfully at {time.ctime()}")
except ValidationError as e:
Response(f"Validation error: {e}")
except Exception as e:
logging.error(f"Error occurred: {e}")
Response(f"An error occurred while creating the document")
class EmployeeAll(generics.ListAPIView):
serializer_class = EmployeeSerializer
queryset = Employee.objects.all()
def get_queryset(self):
queryset = self.queryset
params = self.request.query_params
if "name" in params:
queryset = queryset.filter(name=params["name"])
if "age" in params:
queryset = queryset.filter(age=params["age"])
return queryset
class EmployeeOne(generics.RetrieveUpdateDestroyAPIView):
serializer_class = EmployeeSerializer
lookup_field = "pk"
queryset = Employee.objects.all()
def get_object(self):
try:
queryset = self.get_queryset()
obj = queryset.get(pk=self.kwargs[self.lookup_field])
return obj
except Exception as e:
logging.error(
f"Failed to retrieve document with the ID {self.kwargs[self.lookup_field]}"
)
return Response(
{"detail": "An error occurred while processing your request."}, status=500
)
def update(self, request, *args, **kwargs):
try:
response = super().update(request, *args, **kwargs)
logging.info(
f"Successfully updated document with ID {kwargs[self.lookup_field]}"
)
return response
except ValidationError as e:
logging.error(
f"Failed to update document with ID {kwargs[self.lookup_field]} due to validation error: {e}"
)
return Response({"detail": e.detail}, status=e.status_code)
except DoesNotExist:
return Response({"detail": "Document not found."}, status=404)
except Exception as e:
logging.error(
f"Failed to update document with ID {kwargs[self.lookup_field]} due to an error: {e}"
)
return Response(
{"detail": "An error occurred while processing your request."}, status=500
)
def destroy(self, request, *args, **kwargs):
try:
response = super().destroy(request, *args, **kwargs)
logging.info(
f"Successfully deleted document with ID {kwargs[self.lookup_field]}"
)
return Response(
f"Successfully deleted document with ID {kwargs[self.lookup_field]}"
)
except DoesNotExist:
return Response({"detail": "Document not found."}, status=404)
except Exception as e:
logging.error(
f"Failed to delete document with ID {kwargs[self.lookup_field]} due to an error: {e}"
)
return Response(
{"detail": "An error occurred while processing your request."}, status=500
)
from django.urls import path from .views import EmployeeAdd, EmployeeAll, EmployeeOne
urlpatterns = [ path("register", EmployeeAdd.as_view()), path("employees", EmployeeAll.as_view()), path("employee/<int:pk>", EmployeeOne.as_view()), ]
Any help would be very much appreciated. Thank you.
I tried using serializer, serializer_class changed the methods but still getting the AttributeError:
AttributeError: "Got AttributeError when attempting to get a value for field nameon serializerEmployeeSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Response instance. Original exception text was: 'Response' object has no attribute 'name'."

Flutter build error on iOS after adding web support

I created a flutter web app.
This app is working well but I want to export it as an iOS app to use it on my phone.
When I try to build the app, I get this error :
Launching lib/main.dart on iPhone in debug mode...
Automatically signing iOS for device deployment using specified development team in Xcode project: QJAXXXXXXX
Xcode build done. 56,0s
Failed to build iOS app
Error output from Xcode build:
↳
2022-04-27 16:41:52.572 xcodebuild[91214:1008948] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTiOSFrameworks/DVTiOSFrameworks-19114/DTDeviceKitBase/DTDKRemoteDeviceData.m:373
Details: (null) deviceType from 00008030-001E2CC81E9A402E was NULL when -platform called.
Object: <DTDKMobileDeviceToken: 0x7f8b64b380a0>
Method: -platform
Thread: <NSThread: 0x7f8b60b20e60>{number = 2, name = (null)}
Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide.
2022-04-27 16:41:52.771 xcodebuild[91214:1008959] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTiOSFrameworks/DVTiOSFrameworks-19114/DTDeviceKitBase/DTDKRemoteDeviceData.m:373
Details: (null) deviceType from 00008030-001E2CC81E9A402E was NULL when -platform called.
Object: <DTDKMobileDeviceToken: 0x7f8b64b380a0>
Method: -platform
Thread: <NSThread: 0x7f8b6427c7f0>{number = 10, name = (null)}
Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide.
2022-04-27 16:41:52.845 xcodebuild[91214:1008959] DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/DVTiOSFrameworks/DVTiOSFrameworks-19114/DTDeviceKitBase/DTDKRemoteDeviceData.m:373
Details: (null) deviceType from 00008030-001E2CC81E9A402E was NULL when -platform called.
Object: <DTDKMobileDeviceToken: 0x7f8b64b380a0>
Method: -platform
Thread: <NSThread: 0x7f8b6427c7f0>{number = 10, name = (null)}
Please file a bug at https://feedbackassistant.apple.com with this warning message and any useful information you can provide.
** BUILD FAILED **
Xcode's output:
↳
Writing result bundle at path:
/var/folders/2z/tz90cc4d63gd7v38j8zm21g80000gn/T/flutter_tools.iZwJm9/flutter_ios_build_temp_dirfoYRV2/temporary_xcresult_bundle
Invalid depfile: /Users/Pierre/AndroidStudioProjects/picomanager/.dart_tool/flutter_build/05d710429877ee87af274badd140677f/kernel_snapshot.d
Invalid depfile: /Users/Pierre/AndroidStudioProjects/picomanager/.dart_tool/flutter_build/05d710429877ee87af274badd140677f/kernel_snapshot.d
Invalid depfile: /Users/Pierre/AndroidStudioProjects/picomanager/.dart_tool/flutter_build/05d710429877ee87af274badd140677f/kernel_snapshot.d
Invalid depfile: /Users/Pierre/AndroidStudioProjects/picomanager/.dart_tool/flutter_build/05d710429877ee87af274badd140677f/kernel_snapshot.d
: Error: Not found: 'dart:html'
import 'dart:html';
^
: Error: Not found: 'dart:html'
import 'dart:html';
^
: Error: Not found: 'dart:html'
import 'dart:html';
^
: Error: Not found: 'dart:html'
import 'dart:html';
^
: Error: Not found: 'dart:js'
export 'dart:js' show allowInterop, allowInteropCaptureThis;
^
: Error: Not found: 'dart:js_util'
export 'dart:js_util';
^
: Error: Not found: 'dart:html'
import 'dart:html';
^
: Error: Type 'Blob' not found.
Blob _createBlobFromBytes(Uint8List bytes, String? mimeType) {
^^^^
: Error: Type 'Blob' not found.
Blob? _browserBlob;
^^^^
: Error: Type 'Element' not found.
late Element _target;
^^^^^^^
: Error: Type 'Blob' not found.
Future<Blob> get _blob async {
^^^^
: Error: Type 'Blob' not found.
Future<Uint8List> _blobToByteBuffer(Blob blob) async {
^^^^
: Error: Type 'Element' not found.
Element Function(String href, String suggestedName) createAnchorElement;
^^^^^^^
: Error: Type 'AnchorElement' not found.
AnchorElement createAnchorElement(String href, String? suggestedName) {
^^^^^^^^^^^^^
: Error: Type 'Element' not found.
void addElementToContainerAndClick(Element container, Element element) {
^^^^^^^
: Error: Type 'Element' not found.
void addElementToContainerAndClick(Element container, Element element) {
^^^^^^^
: Error: Type 'Element' not found.
Element ensureInitialized(String id) {
^^^^^^^
: Error: 'HttpRequest' isn't a type.
final _xhrs = <HttpRequest>{};
^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
- 'Auth' is from 'package:firebase/src/auth.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final nextWrapper = allowInterop((firebase_interop.UserJsImpl? user) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
- 'Auth' is from 'package:firebase/src/auth.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final errorWrapper = allowInterop((e) => changeController.addError(e));
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
- 'Auth' is from 'package:firebase/src/auth.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop((firebase_interop.UserJsImpl? user) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Auth'.
- 'Auth' is from 'package:firebase/src/auth.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/auth.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop(idTokenChangedController.addError),
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'DatabaseReference<T>'.
- 'DatabaseReference' is from 'package:firebase/src/database.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/database.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop((update) => jsify(transactionUpdate(dartify(update))));
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'DatabaseReference<T>'.
- 'DatabaseReference' is from 'package:firebase/src/database.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/database.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final onCompleteWrap = allowInterop(
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Query<T>'.
- 'Query' is from 'package:firebase/src/database.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/database.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final callbackWrap = allowInterop((
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Query<T>'.
- 'Query' is from 'package:firebase/src/database.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/database.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
jsObject.once(eventType, allowInterop(
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'DataSnapshot'.
- 'DataSnapshot' is from 'package:firebase/src/database.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/database.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final actionWrap = allowInterop((d) => action(DataSnapshot.getInstance(d)));
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Messaging'.
- 'Messaging' is from 'package:firebase/src/messaging.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/messaging.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final nextWrapper = allowInterop((payload) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Messaging'.
- 'Messaging' is from 'package:firebase/src/messaging.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/messaging.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final errorWrapper = allowInterop(controller.addError);
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Messaging'.
- 'Messaging' is from 'package:firebase/src/messaging.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/messaging.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final nextWrapper = allowInterop((payload) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Messaging'.
- 'Messaging' is from 'package:firebase/src/messaging.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/messaging.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final nextWrapper = allowInterop((_) => null);
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Messaging'.
- 'Messaging' is from 'package:firebase/src/messaging.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/messaging.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final errorWrapper = allowInterop((e) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'UploadTask'.
- 'UploadTask' is from 'package:firebase/src/storage.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/storage.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final nextWrapper = allowInterop(
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'UploadTask'.
- 'UploadTask' is from 'package:firebase/src/storage.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/storage.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final onCompletion = allowInterop(() {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'UploadTask'.
- 'UploadTask' is from 'package:firebase/src/storage.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/storage.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop(_changeController.addError),
^^^^^^^^^^^^
: Error: Method not found: 'hasProperty'.
if (js.hasProperty(error, 'message')) {
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
final message = js.getProperty(error, 'message');
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
map[key] = dartify(util.getProperty(jsObject, key));
^^^^^^^^^^^
: Error: Method not found: 'newObject'.
final jsMap = util.newObject();
^^^^^^^^^
: Error: Method not found: 'setProperty'.
util.setProperty(jsMap, key, jsify(value));
^^^^^^^^^^^
: Error: Method not found: 'allowInterop'.
return allowInterop(dartObject);
^^^^^^^^^^^^
: Error: Method not found: 'callMethod'.
util.callMethod(jsObject, method, args);
^^^^^^^^^^
: Error: Method not found: 'promiseToFuture'.
value = await util.promiseToFuture(thenable);
^^^^^^^^^^^^^^^
: Error: Method not found: 'hasProperty'.
if (util.hasProperty(e, 'code')) {
^^^^^^^^^^^
: Error: Method not found: 'allowInterop'.
PromiseJsImpl<S>(allowInterop((
^^^^^^^^^^^^
: Error: Method not found: 'allowInterop'.
allowInterop(c.completeError);
^^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
String get code => util.getProperty(_source, 'code');
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
String get message => util.getProperty(_source, 'message');
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
String get name => util.getProperty(_source, 'name');
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
Object get serverResponse => util.getProperty(_source, 'serverResponse');
^^^^^^^^^^^
: Error: Method not found: 'getProperty'.
String get stack => util.getProperty(_source, 'stack');
^^^^^^^^^^^
: Error: Method not found: 'instanceof'.
return util.instanceof(object, type);
^^^^^^^^^^
: Error: Undefined name 'window'.
Object? start = window;
^^^^^^
: Error: Method not found: 'getProperty'.
start = util.getProperty(start, item);
^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Firestore'.
- 'Firestore' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final updateFunctionWrap = allowInterop((transaction) =>
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'DocumentReference'.
- 'DocumentReference' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop((firestore_interop.DocumentSnapshotJsImpl snapshot) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'DocumentReference'.
- 'DocumentReference' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final errorWrapper = allowInterop((e) => controller.addError(e));
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Query<T>'.
- 'Query' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop((firestore_interop.QuerySnapshotJsImpl snapshot) {
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'Query<T>'.
- 'Query' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
final errorWrapper = allowInterop((e) => controller.addError(e));
^^^^^^^^^^^^
: Error: The method 'allowInterop' isn't defined for the class 'QuerySnapshot'.
- 'QuerySnapshot' is from 'package:firebase/src/firestore.dart' ('../../.pub-cache/hosted/pub.dartlang.org/firebase-9.0.2/lib/src/firestore.dart').
Try correcting the name to the name of an existing method, or defining a method named 'allowInterop'.
allowInterop((s) => callback(DocumentSnapshot.getInstance(s)));
^^^^^^^^^^^^
: Error: The getter 'Url' isn't defined for the class 'XFile'.
- 'XFile' is from 'package:cross_file/src/types/html.dart' ('../../.pub-cache/hosted/pub.dartlang.org/cross_file-0.3.2/lib/src/types/html.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'Url'.
_path = Url.createObjectUrl(_browserBlob);
^^^
: Error: The method 'Blob' isn't defined for the class 'XFile'.
- 'XFile' is from 'package:cross_file/src/types/html.dart' ('../../.pub-cache/hosted/pub.dartlang.org/cross_file-0.3.2/lib/src/types/html.dart').
Try correcting the name to the name of an existing method, or defining a method named 'Blob'.
? Blob(<dynamic>[bytes])
^^^^
: Error: The method 'Blob' isn't defined for the class 'XFile'.
- 'XFile' is from 'package:cross_file/src/types/html.dart' ('../../.pub-cache/hosted/pub.dartlang.org/cross_file-0.3.2/lib/src/types/html.dart').
Try correcting the name to the name of an existing method, or defining a method named 'Blob'.
: Blob(<dynamic>[bytes], mimeType);
^^^^
: Error: 'Blob' isn't a type.
Blob? _browserBlob;
^^^^
: Error: 'Element' isn't a type.
late Element _target;
^^^^^^^
: Error: 'HttpRequest' isn't a type.
late HttpRequest request;
^^^^^^^^^^^
: Error: 'ProgressEvent' isn't a type.
} on ProgressEvent catch (e) {
^^^^^^^^^^^^^
: Error: The getter 'HttpRequest' isn't defined for the class 'XFile'.
- 'XFile' is from 'package:cross_file/src/types/html.dart' ('../../.pub-cache/hosted/pub.dartlang.org/cross_file-0.3.2/lib/src/types/html.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'HttpRequest'.
request = await HttpRequest.request(path, responseType: 'blob');
^^^^^^^^^^^
: Error: 'Blob' isn't a type.
final Blob blob = await _blob;
^^^^
: Error: 'Blob' isn't a type.
final Blob slice = blob.slice(start ?? 0, end ?? blob.size, blob.type);
^^^^
: Error: 'Blob' isn't a type.
Future<Uint8List> _blobToByteBuffer(Blob blob) async {
^^^^
: Error: 'FileReader' isn't a type.
final FileReader reader = FileReader();
^^^^^^^^^^
: Error: The method 'FileReader' isn't defined for the class 'XFile'.
- 'XFile' is from 'package:cross_file/src/types/html.dart' ('../../.pub-cache/hosted/pub.dartlang.org/cross_file-0.3.2/lib/src/types/html.dart').
Try correcting the name to the name of an existing method, or defining a method named 'FileReader'.
final FileReader reader = FileReader();
^^^^^^^^^^
: Error: 'AnchorElement' isn't a type.
final AnchorElement element = _hasTestOverrides
^^^^^^^^^^^^^
: Error: 'AnchorElement' isn't a type.
? _overrides!.createAnchorElement(this.path, name) as AnchorElement
^^^^^^^^^^^^^
: Error: 'Element' isn't a type.
Element Function(String href, String suggestedName) createAnchorElement;
^^^^^^^
: Error: Method not found: 'webOnlyInstantiateImageCodecFromUrl'.
return ui.webOnlyInstantiateImageCodecFromUrl(// ignore: undefined_function, avoid_dynamic_calls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
: Error: The method 'HttpRequest' isn't defined for the class 'BrowserClient'.
- 'BrowserClient' is from 'package:http/src/browser_client.dart' ('../../.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/browser_client.dart').
Try correcting the name to the name of an existing method, or defining a method named 'HttpRequest'.
var xhr = HttpRequest();
^^^^^^^^^^^
: Error: 'AnchorElement' isn't a type.
final AnchorElement element = AnchorElement(href: href);
^^^^^^^^^^^^^
: Error: Method not found: 'AnchorElement'.
final AnchorElement element = AnchorElement(href: href);
^^^^^^^^^^^^^
: Error: 'Element' isn't a type.
void addElementToContainerAndClick(Element container, Element element) {
^^^^^^^
: Error: 'Element' isn't a type.
void addElementToContainerAndClick(Element container, Element element) {
^^^^^^^
: Error: 'Element' isn't a type.
Element? target = querySelector('#$id');
^^^^^^^
: Error: Method not found: 'querySelector'.
Element? target = querySelector('#$id');
^^^^^^^^^^^^^
: Error: 'Element' isn't a type.
final Element targetElement = Element.tag('flt-x-file')..id = id;
^^^^^^^
: Error: Undefined name 'Element'.
final Element targetElement = Element.tag('flt-x-file')..id = id;
^^^^^^^
: Error: Method not found: 'querySelector'.
querySelector('body')!.children.add(targetElement);
^^^^^^^^^^^^^
: Error: Undefined name 'window'.
return window.navigator.vendor == 'Apple Computer, Inc.';
^^^^^^
Unhandled exception:
FileSystemException(uri=org-dartlang-untranslatable-uri:dart%3Ahtml; message=StandardFileSystem only supports file:* and data:* URIs)
#0 StandardFileSystem.entityForUri (package:front_end/src/api_prototype/standard_file_system.dart:34:7)
#1 asFileUri (package:vm/kernel_front_end.dart:623:37)
#2 writeDepfile (package:vm/kernel_front_end.dart:763:21)
<asynchronous suspension>
#3 FrontendCompiler.compile (package:frontend_server/frontend_server.dart:586:9)
<asynchronous suspension>
#4 starter (package:flutter_frontend_server/server.dart:85:12)
<asynchronous suspension>
#5 main (file:///opt/s/w/ir/cache/builder/src/flutter/flutter_frontend_server/bin/starter.dart:13:24)
<asynchronous suspension>
Failed to package /Users/Pierre/AndroidStudioProjects/picomanager.
Command PhaseScriptExecution failed with a nonzero exit code
note: Using new build system
note: Planning
note: Build preparation complete
note: Building targets in parallel
/Users/Pierre/AndroidStudioProjects/picomanager/ios/Pods/Pods.xcodeproj: warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 15.0.99. (in target 'leveldb-library' from project 'Pods')
Result bundle written to path:
/var/folders/2z/tz90cc4d63gd7v38j8zm21g80000gn/T/flutter_tools.iZwJm9/flutter_ios_build_temp_dirfoYRV2/temporary_xcresult_bundle
Could not build the precompiled application for the device.
Error launching application on iPhone.
Exited (sigterm)
Have you ever seen this error before ?
How did you fix it ? I tried to clean the project several times but this is not working.
Is it possible to build a flutter app designed for web on iOS ?
Thank you !
Unfortunately, Flutter builds for mobile platforms break if you have an import of dart:html somewhere in your code.
A solution to this problem can be to use conditional imports, but you have to construct something like this:
downloader.dart
void downloadFile(List<int> data, String fileName) {
throw UnimplementedError('Cannot use the downloader');
}
downloader_mobile.dart
import 'dart:developer';
void downloadFile(List<int> data, String fileName) {
log('Download is not available for mobile.');
}
downloader_web.dart
// ignore_for_file: avoid_web_libraries_in_flutter
import 'dart:convert';
import 'dart:html' as html;
void downloadFile(List<int> data, String fileName) {
final base64encodedData = base64Encode(data);
final anchor = html.AnchorElement(
href: 'data:application/octet-stream;charset=utf-8;'
'base64,$base64encodedData',
)
..setAttribute('download', fileName)
..click();
html.document.body?.children.remove(anchor);
}
And in the consuming class we check for the existence of dart.library.io and dart.library.js to determine if we are in a web or mobile environment.
import 'package:xxx/features/xxx/tools/downloader.dart'
if (dart.library.io) 'package:xxx/features/xxx/tools/downloader_mobile.dart'
if (dart.library.js) 'package:xxx/features/xxx/tools/downloader_web.dart';

How to do 'or' when applying multiple values with the same lookup?

By referring to this article, I was able to implement the method of and search.
Django-filter with DRF - How to do 'and' when applying multiple values with the same lookup?
I want to know how to do or search for multiple keywords using the same field. How can I implement it?
Here is the code:
from rest_framework import viewsets
from django_filters import rest_framework as filters
from .serializers import BookInfoSerializer
from .models import BookInfo
class MultiValueCharFilter(filters.BaseCSVFilter, filters.CharFilter):
def filter(self, qs, value):
# value is either a list or an 'empty' value
values = value or []
for value in values:
qs = super(MultiValueCharFilter, self).filter(qs, value)
return qs
class BookInfoFilter(filters.FilterSet):
title = MultiValueCharFilter(lookup_expr='contains')
# title = MultiValueCharFilter(lookup_expr='contains', conjoined=False) -> get an error
class Meta:
model = BookInfo
fields = ['title']
class BookInfoAPIView(viewsets.ReadOnlyModelViewSet):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
filter_class = BookInfoFilter
if I set conjoined=False like this title = MultiValueCharFilter(lookup_expr='contains', conjoined=False) get an error __init__() got an unexpected keyword argument 'conjoined'
Django 3.2.5
django-filter 2.4.0
djangorestframework 3.12.4
Python 3.8.5
You can try to modify the queryset returned from MultiValueCharFilter
and combine values with operator.
example:
import operator
from functools import reduce
class MultiValueCharFilter(BaseCSVFilter, CharFilter):
def filter(self, qs, value):
expr = reduce(
operator.or_,
(Q(**{f'{self.field_name}__{self.lookup_expr}': v}) for v in value)
)
return qs.filter(expr)
class BookInfoFilter(filters.FilterSet):
title = MultiValueCharFilter(lookup_expr='contains')
class Meta:
model = BookInfo
fields = ['title']
You can try to create a new Class called ListFilter like this:
from django_filters.filters import Filter
from django_filters.conf import settings as django_filters_settings
from django.db.models.constants import LOOKUP_SEP
class ListFilter(Filter):
"""
Custom Filter for filtering multiple values.
"""
def __init__(self, query_param: str, *args, **kwargs):
"""
Override default variables.
Args:
query_param (str): Query param in URL
"""
super().__init__(*args, **kwargs)
self.query_param = query_param
self.distinct = True
def filter(self, qs, value):
"""
Override filter method in Filter class.
"""
try:
request = self.parent.request
values = request.query_params.getlist(self.query_param)
# Remove empty value in array
values = list(filter(None, values))
except AttributeError:
values = []
# Filter queryset by using OR expression when lookup_expr is 'in'
# Else filter queryset by using AND expression
if values and self.lookup_expr == 'in':
return super().filter(qs, values)
for value in set(values):
predicate = self.get_filter_predicate(value)
qs = self.get_method(qs)(**predicate)
return qs.distinct() if self.distinct else qs
def get_filter_predicate(self, value):
"""
This function helps to get predicate for filtering
"""
name = self.field_name
if (
name
and self.lookup_expr != django_filters_settings.DEFAULT_LOOKUP_EXPR
):
name = LOOKUP_SEP.join([name, self.lookup_expr])
return {name: value}
My class above supports filter nested fields using both OR and AND expressions. E.g. about filter title field using OR expression:
class BookInfoFilter(filters.FilterSet):
title = ListFilter(query_param='title')
class Meta:
model = BookInfo
fields = ['title']

how to pass objects with django and ajax?

I have an application in Django 2.0 in which I use a template with an ajax function from which I want to receive the result of a filter but it generates the following error:
TypeError: <QuerySet [<Curso: Curso object (1)>, <Curso: Curso object (2)>, <Curso: Curso object (3)>]> is not JSON serializable
Views.py
def activaAjax(request):
curso = Curso.objects.filter(pk = request.GET['id'])
cursos = Curso.objects.all()
try:
curso.update(estado=Case(When(estado=True, then=Value(False)),When(estado=False, then=Value(True))))
mensaje = "Proceso de ACTIVACIÓN/INACTIVACIÓN correcto!!!"
data = {'mensaje': mensaje, 'cursos':cursos}
return HttpResponse(json.dumps(data), content_type="application/json")
except:
return HttpResponse(json.dumps({"mensaje":"Error"}), content_type='application/json', status = 500)
return HttpResponse(json.dumps({"mensaje":"Error"}), content_type='application/json')
Queryset can not be directly dump in json by json.dumps()
either you should write queryset.values_list('field1',flat=True)
or if you want more than 1 field from object you should write queryset.values_list('field1','field2',..)
convet it to list with list(queryset.values_list('field1','field2',..))
and pass it in your data as
data = { 'corsos' : list(queryset.values_list('field1','field2',..)) }
2) Or you can also do
from django.core import serializers
serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)

JAXB-ElipseLink: Marshaller not validating

I would like my Eclipselink 2.3 Marshaller to perform validation upon marshalling.
I have made sure that the Schema is correctly created by a SchemaFactory, i am passing it to Marshaller.setSchema and i have registered a handler via Marshaller.setEventHandler().
The marshal result is clearly not valid acc. to its Schema (verified in Eclipse), nevertheless i can see that my breakpoint in handleEvent(ValidationEvent event) is never hit.
I am marshalling XML-Fragments using marshal(Object, XMLStreamWriter) and would expect the Marshaller to perform validation on these fragments according to the Schema i passed.
Anybody any idea why this is not happening?
EDIT:
The Validation error that should occur: 2 missing attributes on an element.
The element corresponds to a Java-Object that is contained in a List<>. I am marshalling the List using:
<xml-element java-attribute="listInstance" xml-path="ListWrapperElement/ListElement" type="foo.ElementType" container-type="java.util.ArrayList"/>
The mapping for the element itself:
<java-type name="foo.ElementType" xml-accessor-type="PROPERTY">
<java-attributes>
// just <xml-attribute> elements here
</java-attributes>
</java-type>
Therefore all attributes are marshalled to ListWrapperElement/ListElement/#attribute.
2 of these are missing and not detected by validation.
I have not been able to reproduce the issue that you are seeing. Below is what I have tried (adapted from the follow blog post):
http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html
MarshalDemo (adapted from blog post)
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.eclipse.persistence.Version;
public class MarshalDemo {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setName("Jane Doe");
customer.getPhoneNumbers().add(new PhoneNumber());
customer.getPhoneNumbers().add(new PhoneNumber());
customer.getPhoneNumbers().add(new PhoneNumber());
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("src/blog/jaxb/validation/customer.xsd"));
JAXBContext jc = JAXBContext.newInstance(Customer.class);
System.out.println(jc.getClass());
System.out.println(Version.getVersion());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setSchema(schema);
marshaller.setEventHandler(new MyValidationEventHandler());
XMLStreamWriter xsw = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
marshaller.marshal(customer, xsw);
}
}
Output
class org.eclipse.persistence.jaxb.JAXBContext
2.3.0
EVENT
SEVERITY: 1
MESSAGE: cvc-maxLength-valid: Value 'Jane Doe' with length = '8' is not facet-valid with respect to maxLength '5' for type 'stringWithMaxSize5'.
LINKED EXCEPTION: org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException: cvc-maxLength-valid: Value 'Jane Doe' with length = '8' is not facet-valid with respect to maxLength '5' for type 'stringWithMaxSize5'.
LOCATOR
LINE NUMBER: -1
COLUMN NUMBER: -1
OFFSET: -1
OBJECT: forum8924293.Customer#ef2c60
NODE: null
URL: null
EVENT
SEVERITY: 1
MESSAGE: cvc-type.3.1.3: The value 'Jane Doe' of element 'name' is not valid.
LINKED EXCEPTION: org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException: cvc-type.3.1.3: The value 'Jane Doe' of element 'name' is not valid.
LOCATOR
LINE NUMBER: -1
COLUMN NUMBER: -1
OFFSET: -1
OBJECT: forum8924293.Customer#ef2c60
NODE: null
URL: null
EVENT
SEVERITY: 1
MESSAGE: cvc-complex-type.2.4.d: Invalid content was found starting with element 'customer'. No child element '{phone-number}' is expected at this point.
LINKED EXCEPTION: org.eclipse.persistence.oxm.record.ValidatingMarshalRecord$MarshalSAXParseException: cvc-complex-type.2.4.d: Invalid content was found starting with element 'customer'. No child element '{phone-number}' is expected at this point.
LOCATOR
LINE NUMBER: -1
COLUMN NUMBER: -1
OFFSET: -1
OBJECT: forum8924293.Customer#ef2c60
NODE: null
URL: null
<?xml version="1.0"?><customer><name>Jane Doe</name><phone-number></phone-number><phone-number></phone-number><phone-number></phone-number></customer>

Resources