How to get a value of particular field inside loop Django - django

I want to print values of 'sm' inside loop
alist = [
{'price': '700', 'sizes': {'sm': True, 'md': False, 'lg': True, 'xl': True} },
{'price': '900', 'sizes': {'sm': False, 'md': True, 'lg': True, 'xl': True} }
]
for i in alist :
print(i.get('sizes'['sm']))

Revise print code.
alist = [
{'price': '700', 'sizes': {'sm': True, 'md': False, 'lg': True, 'xl': True} },
{'price': '900', 'sizes': {'sm': False, 'md': True, 'lg': True, 'xl': True} }
]
for i in alist :
print(i['sizes']['sm'])

Related

Django Framework Rest match calendar users with current user

I am doing an exercise where the goal it's to match my current calendar with other users.
To do this, I created a UserProfile App and Schedule App. Each user has a profile that can have multiple intervals.
Considering my current calendar:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"id": 3,
"user": {
"id": 3,
"username": "john.doe",
"first_name": "John",
"last_name": "Doe"
},
"calendar": [
{
"id": 1,
"mon": true,
"tue": true,
"wed": true,
"thu": true,
"fri": true,
"sat": true,
"sun": true,
"start_date": "09:30",
"end_date": "12:20"
},
{
"id": 2,
"mon": true,
"tue": true,
"wed": true,
"thu": true,
"fri": true,
"sat": true,
"sun": true,
"start_date": "14:00",
"end_date": "23:00"
}
]
}
]}
When I am doing a call to the endpoint /api/search/users it returns all User Profiles with info from each user.
example:
{
"count": 99,
"next": "http://localhost:8000/api/search/users?page=2",
"previous": null,
"results": [
{
"id": 1,
"user": {
"id": 1,
"username": "john.bender.99",
"first_name": "John",
"last_name": "Bender"
},
"calendar": [
{
"id": 2,
"mon": true,
"tue": true,
"wed": true,
"thu": false,
"fri": true,
"sat": false,
"sun": false,
"start_date": "09:30",
"end_date": "12:20"
},
{
"id": 55,
"mon": false,
"tue": true,
"wed": true,
"thu": false,
"fri": true,
"sat": false,
"sun": false,
"start_date": "14:30",
"end_date": "19:20"
}
]
}
]}
Now, what I want to do actually is a search for related users with my calendar to know what days/hours we have a match.
When I do a call to this endpoint /api/search/users?related=self, I want to see this
{
"count": 2,
"results": [
{
"id": 87,
"user": {
"id": 87,
"username": "diana.taller",
"first_name": "Diana",
"last_name": "Taller"
},
"calendar": [
{
"id": 2,
"mon": true,
"tue": true,
"wed": true,
"thu": false,
"fri": true,
"sat": false,
"sun": false,
"start_date": "10:30",
"end_date": "11:20"
},
{
"id": 55,
"mon": false,
"tue": true,
"wed": true,
"thu": false,
"fri": true,
"sat": false,
"sun": false,
"start_date": "16:30",
"end_date": "17:20"
}
]
},{
"id": 128,
"user": {
"id": 128,
"username": "therockjosh",
"first_name": "Josh",
"last_name": "Bail"
},
"calendar": [
{
"id": 2,
"mon": false,
"tue": false,
"wed": false,
"thu": false,
"fri": true,
"sat": false,
"sun": false,
"start_date": "10:30",
"end_date": "11:20"
},
{
"id": 55,
"mon": false,
"tue": false,
"wed": false,
"thu": false,
"fri": true,
"sat": true,
"sun": true,
"start_date": "14:30",
"end_date": "17:00"
}
]
}
]}
The interception between my availability and from users is done between per day and then each interval to see when we have a match.
Inside my Search App, I created this
if related == "self":
current_user_profile = UserProfile.objects.filter(user=self.request.user)
related_users = UserProfile.objects.filter(calendar__in=current_user_profile.calendar.all())
return related_users
If I call current_user_profile, returns me the current user data as I provided you before.
If I call UserProfile.objects.all(), returns me the user's data as I provided you before.
But for some reason, I can't call calendar from current_user_profile.calendar as this image shows.
Is anyone have some idea how could I do this?
I think you need to use get function if you wanna get the object.
if related == "self":
# not UserProfile.objects.filter in order to get the UserProfile object.
current_user_profile = UserProfile.objects.get(user=self.request.user)
related_users = UserProfile.objects.filter(calendar__in=current_user_profile.calendar.all())
return related_users
Here we have the solution I found to exclude my user from the search.
current_user_profile = UserProfile.objects.get(user=self.request.user)
related_users = UserProfile.objects\
.filter(calendar__in=current_user_profile.calendar.all()) \
.exclude(user_id=current_user_profile.id)
return related_users

is there any way to initialize dynamically created 2D array

#define ROWS 5
#define COLUMNS 5
int main(void)
{
bool *p = new bool[ROWS * COLUMNS] = {
{false, true, false, true, true},
{true, false, true, false, true},
{false, true, false, false, false},
{true, false, false, false, true},
{true, true, false, true, false}
};
}
// [Warning] extended initializer lists only available with std=c++11 or-std=gnu++11
// [Error] lvalue required as left operand of assignment
What is the problem here and how it can be resolved?
What you have trying to do is define a one-dimension array and initialized it like a two-dimension array, in that case, you should choose one of the following:
One-Dimention array:
bool bool_arr[ROWS * COLUMNS] = {
false, true, false, true, true,
true, false, true, false, true,
false, true, false, false, false,
true, false, false, false, true,
true, true, false, true, false
};
Two-Dimention array:
bool bool_mat[ROWS][COLUMNS] = {
{false, true, false, true, true},
{true, false, true, false, true},
{false, true, false, false, false},
{true, false, false, false, true},
{true, true, false, true, false}
};

Jest - No tests found

I have specific situation. I have something like common module that define common behaviour of all integrations and all integrations is using that as a library. In that common module, I have configuration of jest and set of tests.
Everything works OK in case that common module is linked (npm link) to integration. But when this this common module is installed directly from npm, jest is not able to find any tests. I suppose, there are some files ignored, but I was not abe to find any configuration that would solve this situation.
Final configuration from debug mode looks like this:
{
"configs": [
{
"automock": false,
"cache": true,
"cacheDirectory": "/private/var/folders/mv/v_zhxfq113qf8d6vsf4ldwq80000gn/T/jest_dx",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"cwd": "<path>/Workspace/integration/my_integration",
"detectLeaks": false,
"detectOpenHandles": false,
"errorOnDeprecated": false,
"extraGlobals": [],
"forceCoverageMatch": [],
"globals": {},
"haste": {
"computeSha1": false,
"throwOnModuleCollision": false
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"ts",
"tsx",
"node"
],
"moduleNameMapper": [],
"modulePathIgnorePatterns": [],
"name": "24eedccdafdba030f3d9209ab1064c8e",
"prettierPath": "prettier",
"resetMocks": false,
"resetModules": false,
"restoreMocks": false,
"rootDir": "<path>/Workspace/integration/my_integration/node_modules/common_module/tests/api",
"roots": [
"<path>/Workspace/integration/my_integration/node_modules/common_module/tests/api"
],
"runner": "jest-runner",
"setupFiles": [],
"setupFilesAfterEnv": [],
"skipFilter": false,
"slowTestThreshold": 5,
"snapshotSerializers": [],
"testEnvironment": "<path>/Workspace/integration/my_integration/node_modules/jest-environment-node/build/index.js",
"testEnvironmentOptions": {},
"testLocationInResults": false,
"testMatch": [
"**/__tests__/**/*.[jt]s?(x)",
"**/?(*.)+(spec|test).[tj]s?(x)"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": [],
"testRunner": "<path>/Workspace/integration/my_integration/node_modules/jest-jasmine2/build/index.js",
"testURL": "http://localhost",
"timers": "real",
"transform": [],
"transformIgnorePatterns": [
"/node_modules/",
"\\.pnp\\.[^\\/]+$"
],
"watchPathIgnorePatterns": []
}
],
"globalConfig": {
"bail": 0,
"changedFilesWithAncestor": false,
"collectCoverage": false,
"collectCoverageFrom": [],
"coverageDirectory": "<path>/Workspace/integration/my_integration/node_modules/common_module/coverage",
"coverageProvider": "babel",
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"detectLeaks": false,
"detectOpenHandles": false,
"errorOnDeprecated": false,
"expand": false,
"findRelatedTests": false,
"forceExit": false,
"json": false,
"lastCommit": false,
"listTests": false,
"logHeapUsage": false,
"maxConcurrency": 5,
"maxWorkers": 7,
"noStackTrace": false,
"nonFlagArgs": [],
"notify": false,
"notifyMode": "failure-change",
"onlyChanged": false,
"onlyFailures": false,
"passWithNoTests": false,
"projects": [],
"rootDir": "<path>/Workspace/integration/my_integration/node_modules/common_module/tests/api",
"runTestsByPath": false,
"skipFilter": false,
"testFailureExitCode": 1,
"testPathPattern": "",
"testSequencer": "<path>/Workspace/integration/my_integration/node_modules/#jest/test-sequencer/build/index.js",
"updateSnapshot": "new",
"useStderr": false,
"verbose": true,
"watch": false,
"watchAll": false,
"watchman": true
},
"version": "26.4.0"
}
All tests are defined on path <path>/Workspace/integration/my_integration/node_modules/common_module/tests/api named as e.g. something.test.js.
Console will show allways:
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
No files found in <path>/Workspace/integration/my_integration/node_modules/common_module/tests/api.
Make sure Jest's configuration does not exclude this directory.
To set up Jest, make sure a package.json file exists.
Jest Documentation: facebook.github.io/jest/docs/configuration.html
Pattern: - 0 matches
npm ERR! Test failed. See above for more details.

NLTK NaiveBayesClassifier throws attribute error stating 'list' object has no attribute 'items'

I am trying to train a dataset with NLTK's Naive Bayes Classifier but my terminal keeps throwing this error
# Applying Naive Bayes
training_set = featursets[:2000]
testing_set = featursets[2000:]
classifier = nltk.NaiveBayesClassifier.train(training_set)
print "Naive bayes classifier accuracy % = ", (nltk.classify.accuracy(classifier, testing_set)*100)
classifier.show_informative_features(30)
And The error says:
AttributeError
Traceback (most recent call last)
<ipython-input-69-2a409562c9f8> in <module>()
2 training_set = featursets[:2000]
3 testing_set = featursets[2000:]
----> 4 classifier = nltk.NaiveBayesClassifier.train(featursets)
5 print "Naive bayes classifier accuracy % = "(nltk.classify.accuracy(classifier, testing_set)*100)
6 classifier.show_informative_features(30)
/home/satyaki/.local/lib/python2.7/site-packages/nltk/classify/naivebayes.pyc in train(cls, labeled_featuresets, estimator)
194 for featureset, label in labeled_featuresets:
195 label_freqdist[label] += 1
--> 196 for fname, fval in featureset.items():
197 # Increment freq(fval|label, fname)
198 feature_freqdist[label, fname][fval] += 1
AttributeError: 'list' object has no attribute 'items'
But I'm not sure what went wrong here. Any help, guys?
Make your feature values as a dictionary.
Source : reference link
Snippet from train data[0] :
({'able': True,
'absurdly': True,
'alone': True,
'american': True,
'americans': True,
'anyone': True,
'appearance': True,
'applauding': True,
'atrocious': True,
'audience': True,
'audiences': True,
'aykroyd': True,
'bacall': True,
'band': True,
'banter': True,
'bicker': True,
'bits': True,
'brothers': True,
'chief': True,
'clude': True,
'comedy': True,
'commander': True,
'counted': True,
'crap': True,
'current': True,
'dan': True,
'dialogue': True,
'discriminating': True,
'dorothy': True,
'drowned': True,
'elvis': True,
'especially': True,
'even': True,
'ex': True,
'exchange': True,
'fellow': True,
'film': True,
'fine': True,
'first': True,
'fit': True,
'forget': True,
'former': True,
'funny': True,
'garner': True,
'gay': True,
'get': True,
'gets': True,
'going': True,
'grumpy': True,
'heard': True,
'heaven': True,
'help': True,
'holiday': True,
'honestly': True,
'immediately': True,
'impersonator': True,
'including': True,
'ing': True,
'ish': True,
'jack': True,
'james': True,
'john': True,
'joke': True,
'judas': True,
'lady': True,
'lauren': True,
'lemmon': True,
'macarena': True,
'march': True,
'marching': True,
'men': True,
'merely': True,
'mine': True,
'moment': True,
'movie': True,
'musical': True,
'non': True,
'number': True,
'offensively': True,
'old': True,
'older': True,
'one': True,
'overbearing': True,
'penis': True,
'perfect': True,
'performing': True,
'raw': True,
'references': True,
'resist': True,
'rest': True,
'ritual': True,
'road': True,
'room': True,
'scores': True,
'seeing': True,
'silence': True,
'single': True,
'slot': True,
'sold': True,
'star': True,
'submit': True,
'supporting': True,
'sure': True,
'talkin': True,
'tarheels': True,
'yup': True},
'negative')

Item assignment to Python dask array objects

I've created a Python dask array and I'm trying to modify a slice of the array as follows:
import numpy as np
import dask.array as da
x = np.random.random((20000, 100, 100)) # Create numpy array
dx = da.from_array(x, chunks=(x.shape[0], 10, 10)) # Create dask array from numpy array
dx[:50, :, :] = 0 # Modify a slice of the dask array
Such an attempt to modify the dask array raises the exception:
TypeError: 'Array' object does not support item assignment
Is there a way to modify a dask array slice without raising an exception?
Currently dask.array does not support item assignment or any other mutation operation.
In the case above I recommend concatenating with zeros
In [1]: import dask.array as da
In [2]: dx = da.random.random((20000 - 50, 100, 100), chunks=(None, 10, 10))
In [3]: z = da.zeros((50, 100, 100), chunks=(50, 10, 10))
In [4]: dx2 = da.concatenate([z, dx], axis=0)
In [5]: dx2
Out[5]: dask.array<concate..., shape=(20000, 100, 100), dtype=float64, chunksize=(50, 10, 10)>
In [6]: (dx2 == 0)[0:100, 0, 0].compute()
Out[6]:
array([ True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True, True,
True, True, True, True, True, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False, False], dtype=bool)
The da.where(condition, iftrue, iffalse) function can also be quite useful in working around cases where mutation is often desired.