Tech C**P
14 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
In Python you can use setattr to set an attribute on a class. Let's say we have a very simple class like below:

class User:
def register(self, key, val):
setattr(self, key, val)


Now if you want to set an attribute called name on User class:

>>> user = User()
>>> user.register('name', 'alireza')
>>> user.name
'alireza'

With a little bit of code you can automatically get data from a source and set dynamic attributes.

#python #setattr
What is zip function in Python?

zip function gets iterables as input and returns a tuple as output, it actually aggregates data:

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Returns a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

So the syntax is:

zip(*iterables)


The real world example:

numberList = [1, 2, 3]
strList = ['one', 'two', 'three']

# Two iterables are passed
result = zip(numberList, strList)

{(2, 'two'), (3, 'three'), (1, 'one')}


If number of elements differ:

numbersList = [1, 2, 3]

numbersTuple = ('ONE', 'TWO', 'THREE', 'FOUR')

result = zip(numbersList, numbersTuple)

print(set(result))
{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}

As you can see from above, list is truncated to the length of the shortest argument sequence numbersList.


You can also use zip to actually unzip data:

coordinate = ['x', 'y', 'z']
value = [3, 4, 5, 0, 9]

result = zip(coordinate, value)
resultList = list(result)
print(resultList)

c, v = zip(*resultList)
print('c =', c)
print('v =', v)

The output:

[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)

#python #zip #unzip #iterators
If your pyCharm does not recognize specific python files as a Python file and does not provide syntax highlighting for you, you need to navigate to File > Settings > Editor > File Types > Text and Under Registered Patterns, you can see the new myfilename.py in the list. Remove it from the list with the - button and click OK at the end.

#python #pycharm #file_types #syntax_highlighting
How to start a jetbrains license server on your own host using Docker:

docker run -d -p 8000:80 --name jetbrains-license-server \
-e TZ="Europe/Paris" \
-e JLS_VIRTUAL_HOSTS=jetbrains-license-server.example.com \
-v $(pwd)/data:/data \
crazymax/jetbrains-license-server:latest


There are many env variables you can set as JLS_VIRTUAL_HOSTS above:

TZ : The timezone assigned to the container (default UTC)
JLS_VIRTUAL_HOSTS : Virtual hosts where license server will be available (comma delimited for several hosts)
JLS_CONTEXT : Context path used by the license server (default /)
JLS_ACCESS_CONFIG : JSON file to configure user restrictions (default /data/access-config.json)
JLS_STATS_RECIPIENTS : Reports recipients email addresses for stats (comma delimited)
JLS_REPORT_OUT_OF_LICENSE : Warn about lack of licenses every hour following the percentage threshold (default 0)
JLS_SMTP_SERVER : SMTP server host to use for sending stats (stats disabled if empty)
JLS_SMTP_PORT : SMTP server port (default 25)
JLS_SMTP_USERNAME : SMTP username (auth disabled if empty)
JLS_SMTP_PASSWORD : SMTP password (auth disabled if empty)
JLS_STATS_FROM : From address for stats emails
JLS_STATS_TOKEN : Enables an auth token for the stats API at /reportApi (HTTP POST)

Volumes:
/data : Contains registration data and configuration

Ports:
`80 : Jetbrains License Server HTTP port

Github removes repos related to crack and license, copy or download content from the below link:

- https://github.com/crazy-max/docker-jetbrains-license-server

#docker #license_server #jetbrains #crazymax
If you use Icinga2 you are difinitely familiar with snmp. There are times that you need to debug the system. For exampe to see if
you can connect to snmp on the other side (firewall issues), or to find a specific mib.

For this you can use snmpwalk as below:

snmpwalk -Os -c YOUR_COMMUNITY_STRING -v 1 YOUR_SNMP_IP_ADDRESS

NOTE: this command is ran from Icinga2 server.

NOTE: snmp should be installed on server you want to monitor: apt-get install snmpd

#snmp #snmpd #snmpwalk
Sharing a piece of code in order to get a solution is a way everone follows, but the difference is about people who shares a piece of code professionally and those who just takes a picture from the screen in front! You should be happy in case the artistic photo is straight otherwise you have to tilt your head :)))

One of the greatest tools to do this job is codeshare. ou paste your code there and other people involve into the code concurrently with you.

Head over to link below to and use websites similar to the below website to share codes, never ever ever share a code with a photo taken from screen. This shows how negligible the time is for you and the person you're asking from, `cause it takes much more time to see what is on the screen:

- https://codeshare.io/

#codeshare #codeshare_io
Have you seen some backup disks that has just an ethernet port like WD (western digital) with 8TB of capacity? if you don't know some commands to mount them or access its dashbaord, things could get a little bit harder.

LED color in front of the disk:
- blue LED is blinking: getting ready to serve data (if disk is almost full it may take 2 to 3 hours)

- blue LED is on with no blinking: LAN is connected and device is ready.

- red LED is blinking: there is something wrong with the device, maybe bad cluster or something else!

- red LED is not blinking: Device is ready, but LAN cable is not connected.

This LED color and its behaviour is almost always the same on other devices too. So memorize them :)

To get the IP address of WD (My Cloud) ping the domain as below:
ping wdmycloud.local

To see the GUI dashbaord open a browser and head over to:
- https://wdmycloud.local

To mount the device first check that the blue LED is on without blinking on the disk then create the destination directory if not exist:
mkdir -p /mnt/my_backup_folder

Now mount the disk with the command below (you can see folders like MyFolder from dashboard->Shares menu):
sudo mount -t nfs MyCloudIPAddress:/nfs/MyFolder /mnt/my_backup_folder


NOTE: dashboard default username is admin and it has no password by default.

NOTE: if you want to reset the password: https://support.wdc.com/knowledgebase/answer.aspx?ID=13986

#wd #my_cloud #backup_disk #western_digital #wdmycloud
How to get file mimetype in Python?

pip install python-magic

Now get file mime type like below:

>>> magic.from_file("testdata/test.pdf", mime=True)
'application/pdf'


If you do not provide mime=True:

>>> magic.from_file("testdata/test.pdf")
'PDF document, version 1.2'


If you are on OS X you may get the below error:

ImportError: failed to find libmagic.  Check your installation


To solve the problem install libmagic using brew:

brew install libmagic


Or using macport:

port install file

Read more here:
- https://github.com/ahupp/python-magic

#python #python_magic #magic #mimetype #mime #libmagic
How to upload file into Amazon object storage using boto3?

pip install boto3


Now you just need the region, endpoint and access key, secret key which you would be given after purchase:

client = session.client('s3',
region_name=YOUR_REGION,
endpoint_url=YOUR_HOST,
aws_access_key_id=YOUR_ACCESS_KEY,
aws_secret_access_key=YOUR_SECRET_KEY)

client.upload_file(file_path, # Path to local file
obj_config['spacename'], # Name of Space
'YOUR_FILE_NAME.txt', # Name for remote file
ExtraArgs={"Metadata": {'user-id': USER_ID} }) # metadata

NOTE: in the name of the file you can pass / like my/file/here.txt. Now it will create directory (virtually) in the remote object storage.

#python #object_storage #boto3 #file_upload
Any time scientists disagree, it's because we have insufficient data. Then we can agree on what kind of data to get; we get the data; and the data solves the problem. Either I'm right or you're right, or we're both wrong. And we move on.

Neil deGrasse Tyson

#kafka #ebook
How to ignore extra fields for schema validation in Mongoengine?

Some records currently have extra fields that are not included in my model schema (by error, but I want to handle these cases). When I try to query the DB and transform the records into the schema, I get the following error:

FieldDoesNotExist
The field 'X' does not exist on the document 'Y'



For ignoring this error when having extra fields while getting data, set strict to False in your meta dictionary.


class User(Document):
email = StringField(required=True, unique=True)
password = StringField()
meta = {'strict': False}



#mongodb #mongo #python #mongoengine #strict #FieldDoesNotExist
In MongoDB you can remove duplicate documents based on a specific field:

db.yourCollection.aggregate([
{ "$group": {
"_id": { "yourDuplicateKey": "$yourDuplicateKey" },
"dups": { "$push": "$_id" },
"count": { "$sum": 1 }
}},
{ "$match": { "count": { "$gt": 1 } }}
]).forEach(function(doc) {
doc.dups.shift();
db.yourCollection.remove({ "_id": {"$in": doc.dups }});
});

It uses aggregation to group by based on the given key then add its _id into dups field and its count in count field. It will project fields with count of more than 1 using $match. At the end loops over each document and remove all duplicate fields except the first one (`shift` will cause this behaviour).

#mongodb #mongo #duplicates #duplication