Saturday, December 29, 2018

android kotlin ArrayAdapter withen JSONObject itemdata

private inner class StableArrayAdapter(context: Context, viewResourceId: Int)
    : ArrayAdapter<JSONObject>(context, viewResourceId) {

    fun addItems(items: JSONArray) {
        for (i in 0 until items.length()) {
            val item = items.getJSONObject(i)
            this.add(item)
        }
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var retView: View? = null        if (convertView == null) {
            retView = LayoutInflater.from(getContext()).inflate(R.layout.main_row_item, parent, false)
        } else {
            retView = convertView
        }
        val item = getItem(position) as JSONObject
        retView!!.tag = item

        if (item.optBoolean("is_denied"))
            retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_odo_maroon)
        else {
            if (item.optBoolean("is_received"))
                retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_disable_blue)
            else {
                if (item.optBoolean("is_approved"))
                    retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_odo_orange)
                else {
                    if (item.optBoolean("is_sent"))
                        retView!!.icon_state.setBackgroundResource(R.drawable.bg_oval_active_blue)
                    else                        retView!!.icon_state.visibility = View.GONE                }
            }
        }

        val dateStr = item.getString("created_at")
        retView.tv_datetime.setText(AppHelper.formatJsonDate(dateStr))

        val toc = item.getJSONObject("toc")
        val tob = item.getJSONObject("tob")
        retView.tv_name.setText(toc.getString("name") + " / " + tob.getString("name"))
        retView.tv_descr.setText("№ " + item.getString("order_number") + " - " + item.getString("order_name"))

        retView.setOnClickListener { view ->            itemClick(view)
        }        return retView!!
    }

    fun itemClick(view: View) {
        val item = view.tag as JSONObject

        val args = Bundle()
        args.putString(ArgumentPassKeys.ARG_JSON_OBJECT, item.toString())

        val intent = Intent(_context, EventsActivity::class.java)
        intent.putExtras(args)
        _activity!!.startActivityForResult(intent, ActivityPassCodes.ITEM_EDIT)
    }
}

Tuesday, December 25, 2018

flask response svg or png qrcode generator using pyqrcode module

import pyqrcode, png
text = pyqrcode.create('')
text.svg('./app/static/uploads/uca-url.svg', scale=8)
text.png('./app/static/uploads/uca-url.png', scale=8)
# print(text.text())
# print(text.terminal(module_color='red', background='yellow'))
# print(url.terminal(quiet_zone=1))


@users_api.route('/')
def base_index():
import io
import pyqrcode, png
qr = pyqrcode.create('5035265994')
qr.png('test.png', scale=8)
image_binary = io.open("test.png", "rb")
print('***********type is ', type(image_binary))
response = make_response(image_binary.read())
response.headers.set('Content-Type', 'image/png')
# response.headers.set('Content-Disposition', 'attachment', filename='test.png')
return response
# return json_error(), 404

Saturday, December 22, 2018

python switcher case while else type() format (%s %03d {})

b = 'True'
print(type(b) == str)
print(type(b) == bool)

switcher = {
True: print('it is true'),
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
print(switcher.get(True, 'else'))

a = 3
while (a > 0):
print(a)
a -= 1
else:
print("Reached 0")

# Here age is a string object
age = "18"
print(age)
# Converting string to integer
int_age = int(age)
print(int_age)
age = False
int_age = int(age)
print(int_age)

print('%(language)s has %(number)05d quote types.' % {
"language": "Python",
"number": 2
})
print('form({})'.format(b))

Thursday, October 18, 2018

facebook twitter widget on sidebar

<div id="tabs" class="col-sm-9 social-tab-control">
                <div class="col-sm-12">
                    <ul class="social-tab">
                        <li class="facebook">
                            <a href="#facebook-tab"><i class="fa fa-facebook"></i> Facebook</a>
                        </li>
                        <li class="twitter">
                            <a href="#twitter-tab"><i class="fa fa-twitter"></i> Twitter</a>
                        </li>
                    </ul>
                </div>
                <div class="col-sm-12">
                    <div id="facebook-tab">

                        <div class="social-item-wrap">
                            <?php for ($i = 0; $i < 0; $i++): ?>
                                <div class="social-item">
                                    <h5>5 ЦАГИЙН ӨМНӨ</h5>
                                    <a href="#" class="social-link">@suisfacebooklink</a>
                                    <span>СУИС-ийн “Оюутан” театрын тайзнаа тоглох энэ удаагийн “Учиртай гурван толгой” дуурийн Ерөнхий найруулагчаар МУАЖ А.Долгор, удирдаачаар ....</span>
                                </div>
                            <?php endfor; ?>
                        </div>

                    </div>

                    <div id="twitter-tab">

                        <div class="social-item-wrap">

                            <a class="twitter-timeline" data-chrome="nofooter noborders" data-dnt="true" href="https://twitter.com/MSUAC" data-widget-id="637864063012311041">Tweets by @MSUAC</a>
                            <script>!function (d, s, id) {
                                    var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https';
                                    if (!d.getElementById(id)) {
                                        js = d.createElement(s);
                                        js.id = id;
                                        js.src = p + "://platform.twitter.com/widgets.js";
                                        fjs.parentNode.insertBefore(js, fjs);
                                    }
                                }(document, "script", "twitter-wjs");</script>


                        </div>
                    </div>
                </div>

            </div>

Wednesday, August 15, 2018

nginx.conf


#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  api.odo.mn seller.odo.mn supply.odo.mn admin.odo.mn order.odo.mn odo.mn;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}

location / {
proxy_pass http://0.0.0.0:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
    }

server {
listen 80;
server_name login.odo.mn;
location / {
proxy_pass http://0.0.0.0:8002;
proxy_set_header Host login.odo.mn;
}
}


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

Tuesday, July 3, 2018

python your oauth server login using google account integration

from flask import flash, redirect, url_for, session, request, jsonify
from flask_oauthlib.client import OAuth
from app.models.company_models import Company, CompanyInfo, Branch
from app.models.shared_models import Sphere, Business
from app import instance, oauth as my_oauth, my_mail
from app.models.auth_models import User
from flask_login import login_user, logout_user, current_user, login_required
import urllib
from app.helpers.url_helper import base_url
from app.libraries.odo.odo_common import uuid_generator

GOOGLE_CLIENT_ID = '1059700860469-sdfaasdf.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET = 'asdf'
# one of the Redirect URIs from Google APIs console
AUTH_REDIRECT_URI = '/googleauth/callback'

google_oauth = OAuth(instance)

google = google_oauth.remote_app(
'google',
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET,
request_token_params={
'scope': 'email'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
)


@instance.route('/googleauth', methods=['GET', 'POST'])
def googleauth_index():
return redirect(url_for('googleauth_login', **request.args))


@instance.route('/googleauth/login')
def googleauth_login():
session['x_response_type'] = request.args['response_type']
session['x_client_id'] = request.args['client_id']
session['x_redirect_uri'] = request.args['redirect_uri']
session['x_scope'] = request.args['scope']

if 'google_token' in session:
token = session['google_token']
if not token is None:
googleauth_revoke()
session.pop('google_token')

return google.authorize(callback=url_for('googleauth_authorized', _external=True))


@instance.route('/googleauth/logout')
def googleauth_logout():

if 'google_token' in session:
token = session['google_token']
if token:
googleauth_revoke()
session.pop('google_token')

return redirect(base_url('order'))


@instance.route(AUTH_REDIRECT_URI)
def googleauth_authorized():

resp = google.authorized_response()

# try to revoke
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)

session['google_token'] = (resp['access_token'], '')
google_user = google.get('userinfo').data
user = User.query.filter_by(email=google_user['email']).first()

if not user:
new_password = uuid_generator()

user = User()
user.username = google_user['email']
user.email = google_user['email']
user.password = new_password
user.role_id = 6 # new user is admin for your self
try:
user.save()

body = "Google хэрэглэгчээр системд бүртгүүлсэн нууц үг: " + new_password + ""
my_mail.Send("Таны систем дээрх нууц үг", body, [user.email])
except Exception as e:
flash('Хэрэглэгч бүртгэхэд алдаа гарлаа! ' +
str(e), category='error')

if login_user(user):
response_type = session['x_response_type']
client_id = session['x_client_id']
redirect_uri = session['x_redirect_uri']
scope = session['x_scope']
return redirect(url_for('googleauth_confirm_authorization', response_type=response_type, client_id=client_id, redirect_uri=redirect_uri, scope=scope))


@instance.route('/googleauth/confirm', methods=['GET', 'POST'])
@login_required
def googleauth_confirm_authorization():
return my_oauth.confirm_authorization_request()


@google.tokengetter
def googleauth_get_google_oauth_token():
return session.get('google_token')


def googleauth_revoke():
if 'google_token' in session:
token = session['google_token']
if not token is None:
try:
request = urllib.request.Request(
"https://accounts.google.com/o/oauth2/revoke?token=" + token[0])
request.add_header(
"Content-type", "application/x-www-form-urlencoded")
urllib.request.urlopen(request).read()
except Exception as e:
print(e)

Monday, June 25, 2018

python flask mail send example using smtp protocol with google less secure app access

from flask import Flask, Blueprint, url_for
from flask_mail import Mail, Message
import os

mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 587,
"MAIL_USE_TLS": True,
"MAIL_USE_SSL": False,
"MAIL_USERNAME": 'acc@gmail.com',
"MAIL_PASSWORD": 'password',
"DEBUG": True
}

app = Flask(__name__)
app.config.update(mail_settings)

mail = Mail(app)
site = Blueprint('site', __name__)


@site.route('/')
def index():
return '<a href="' + url_for('site.send') + '">send</a>'


@site.route('/send_mail')
def send():
msg = Message(subject="Hello",
sender=app.config.get("MAIL_USERNAME"),
recipients=["boroog@gmail.com"],
body="This is a test email I sent with Gmail and Python!")
mail.send(msg)
return 'SENT'

# flask_mail сан ашиглахгүй гэвэл доорх код бас ажиллана

# # SMTP_SSL Example
# import smtplib
# # server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
# smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
# smtpserver.ehlo()
# smtpserver.starttls()
# smtpserver.ehlo()
# smtpserver.login("acc@gmail.com", "password")
# # ssl server doesn't support or need tls, so don't call server_ssl.starttls()
# smtpserver.sendmail("acc@gmail.com", "boroog@gmail.com", "test message")
# #server_ssl.quit()
# smtpserver.close()
return 'SENT'


app.register_blueprint(site)


if __name__ == '__main__':
app.run('127.0.0.1', 5000)

Tuesday, June 5, 2018

python alembic sqlalchemy base model __init__

from collections import OrderedDict
from flask import json, jsonify

from sqlalchemy import func, text
from sqlalchemy import Column, Boolean, Integer, String, DateTime, ForeignKey
from sqlalchemy.ext.declarative import declared_attr

from app import db


class CoreModel(db.Model):
__abstract__ = True

# __tablename__ = name_model as name
@declared_attr
def __tablename__(cls):
cn = cls.__name__.lower()
_i = cn.rfind('_model')
if _i > 0:
return cn[:_i]
else:
return cn

# result as list
@classmethod
def to_list(cls, query_result, obj_field_names=None):
data_array = []
for result_item in query_result:
item = result_item.as_dict()
if obj_field_names is not None:
for obj_field_name in obj_field_names:
obj_field = getattr(result_item, obj_field_name)
if isinstance(obj_field, CoreModel):
item[obj_field_name] = obj_field.as_dict()
data_array.append(item)
return data_array

# model as dict
def as_dict(self, obj_field_names=None):
data_object = OrderedDict()
for key in self.__mapper__.c.keys():
val_field = getattr(self, key)
if not isinstance(val_field, CoreModel):
data_object[key] = val_field
if obj_field_names is not None:
for obj_field_name in obj_field_names:
obj_field = getattr(self, obj_field_name)
if isinstance(obj_field, CoreModel):
data_object[obj_field_name] = obj_field.as_dict()
return data_object

def addme(self):
db.session.add(self)
return self

def save(self):
db.session.add(self)
db.session.commit()
return self

def rollback(self):
db.session.rollback()
return self

@classmethod
def commit(cls):
db.session.commit()

@classmethod
def execute(cls, sql, params=None):
if params is None:
params = {}
resultproxy = db.engine.execute(text(sql), params)
d, a = {}, []
for rowproxy in resultproxy:
# rowproxy.items() returns an array like [(key0, value0), (key1, value1)]
for tup in rowproxy.items():
# build up the dictionary
d = {**d, **{tup[0]: tup[1]}}
a.append(d)
return a


class BaseModel(CoreModel):
__abstract__ = True

id = Column(Integer, primary_key=True)
created_at = Column(DateTime, server_default=func.now())
modified_at = Column(DateTime, server_default=func.now(),
server_onupdate=func.now())
deleted = Column(Boolean, nullable=False, default=False)

@classmethod
def get_first(self):
return self.query.order_by(self.id.asc()).first()

@classmethod
def get_last(self):
return self.query.order_by(self.id.desc()).first()

@classmethod
def get_list_all(self):
lst = []
for item in self.query.order_by(self.id.asc()).all():
lst.append(item.as_dict())
return lst

@classmethod
def get_list(self, **kwargs):
query = self.query.filter_by(**kwargs)
lst = []
for item in query.order_by(self.id.asc()).all():
lst.append(item.as_dict())
return lst


class FullBaseModel(BaseModel):
__abstract__ = True

created_ip = Column(String(length=50))
created_by = Column(Integer, ForeignKey('user.id'))
modified_ip = Column(String(length=50))
modified_by = Column(Integer, ForeignKey('user.id'))
ordering = Column(Integer, nullable=False, default=0)

bitbucket remove cached some files using git rm -rf command

git rm -rf --cached files 
git commit -a -m "Deleted files" 
git push origin master

Thursday, May 17, 2018

android What is the difference between GridView for dynamicallty add item vs GridLayout for statically view

<GridLayout    android:layout_width="match_parent"    android:layout_height="0dp"    android:layout_weight="2"    android:alignmentMode="alignBounds"    android:rowCount="2"    android:columnCount="2"    android:columnOrderPreserved="false"    android:padding="@dimen/gap16"    android:orientation="horizontal">

    <android.support.v7.widget.CardView        android:layout_columnWeight="1"        android:layout_rowWeight="1"        android:layout_gravity="fill"        android:layout_column="0"        android:layout_row="0"        android:layout_margin="@dimen/gap16"        app:cardCornerRadius="@dimen/gap3"        app:cardElevation="@dimen/gap3">

        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="fill"            android:orientation="vertical">

            <Button                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="button 1"                android:background="@color/colorOdoOrange"                android:textColor="@color/colorWhite" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView        android:layout_columnWeight="1"        android:layout_rowWeight="1"        android:layout_gravity="fill"        android:layout_column="1"        android:layout_row="1"        android:layout_margin="@dimen/gap16"        app:cardCornerRadius="@dimen/gap3"        app:cardElevation="@dimen/gap16">

        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_gravity="fill"            android:orientation="vertical">

            <Button                android:layout_width="match_parent"                android:layout_height="wrap_content"                android:text="button 2"                android:background="@color/colorOdoOrange"                android:textColor="@color/colorWhite" />
        </LinearLayout>
    </android.support.v7.widget.CardView>

</GridLayout>


VS


<mn.odo.ordersystem.components.OdoGridView    android:id="@+id/lv_goods_images"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_marginTop="@dimen/gap16"    android:layout_marginBottom="@dimen/gap16"    android:isScrollContainer="false"    android:columnWidth="0dp"    android:gravity="center"    android:numColumns="5"    android:stretchMode="columnWidth"    android:horizontalSpacing="@dimen/gap0"    android:verticalSpacing="@dimen/gap0" />


gridview item:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical">

    <Button        android:id="@+id/item_image"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@color/colorBgSubTitleBlue"        android:text="button 0" />

</LinearLayout>

Sunday, May 13, 2018

android kotlin tablayout child tab ViewGroup.MarginLayoutParams setMargins, setPadding with padding dp to px

val slidingTabStrip = tabs.getChildAt(0) as ViewGroup
for (i in 0 until slidingTabStrip.childCount - 1) {
    val v = slidingTabStrip.getChildAt(i)
    val p = v.getLayoutParams() as ViewGroup.MarginLayoutParams
    p.setMargins(0, 0, 0, 0)

    val scale = resources.displayMetrics.density
    var pxl = resources.getDimensionPixelSize(R.dimen.gap1)
    val padding_in_dp = 3    val padding_in_px = (padding_in_dp * scale + 0.5f).toInt()
    v.setPadding(pxl, pxl, pxl, pxl)
}

Saturday, May 12, 2018

android activity theme customize colors

<activity    android:name=".LoginActivity"    
android:label="@string/app_name"    
android:screenOrientation="portrait"    
android:theme="@style/LoginTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


<!-- Login application theme. --><style name="LoginTheme" 
parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="LoginTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>


  • colorPrimary – The color of the app bar.
  • colorPrimaryDark – The color of the status bar and contextual app bars; this is normally a dark version of colorPrimary.
  • colorAccent – The color of UI controls such as check boxes, radio buttons, and edit text boxes.
  • windowBackground – The color of the screen background.
  • textColorPrimary – The color of UI text in the app bar.
  • statusBarColor – The color of the status bar.
  • navigationBarColor – The color of the navigation bar.
you can use following link to setup your style.

Tuesday, May 1, 2018

python Flask, make_response, redirect, session, url_for

from flask import Flask, make_response, redirect, session, url_for

SECRET_KEY = 'develop'

app = Flask(__name__)
app.config.from_object(__name__)

@app.route('/')
def index():
    return '<a href="%s">Go here.</a>' % url_for('do_redirect')

@app.route('/redirect/')
def do_redirect():
    session['hello'] = 'world!'
    return redirect(url_for('dump_session'))

@app.route('/session/')
def dump_session():
    response = make_response(repr(session))
    response.content_type = 'text/plain'
    return response

if __name__ == '__main__':
    app.run()

Monday, April 30, 2018

android check whether internet is available or not.

//check whether internet is available or not.
    public boolean isReachable(String address, int port, int timeoutMs) {
        try {
            Socket sock = new Socket();
            SocketAddress sockaddr = new InetSocketAddress(address, port);

            sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
            sock.close();

            return true;

        } catch (IOException e) { return false; }
    }