etc/module.xml

Criação e possíveis configurações no arquivo etc/module.xml

CLI

Comandos que podem ser executados usando CLI do Magento 2
## Activating a new module
```bash```
bin/magento module:enable Cammino_CustomBlocks
```

## Updating all modules database scripts
```bash```
bin/magento setup:upgrade
```

Basic Module Structure

Estrutura básica de um módulo no Magento 2
# Basic Module Structure

all new Magento 2 modules should be created in **app/code**/namespace/modulename

**Exemple:**
*app/code/Cammino/CustomBlocks*

## Folder structure
- app/
    - code/
        - Cammino/
            - Customblocks/
                - etc/
                    - module.xml 
                - registration.php

Get Foreground App

Crashes on devices before Lolipop
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public String getForegroundApp(Context context) {
        String currentApp = "NULL";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            try {
                Class.forName( "android.app.usage.UsageStatsManager" );
                UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
                long time = System.currentTimeMillis();
                List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
                if (appList != null && appList.size() > 0) {
                    SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
                    for (UsageStats usageStats : appList) {
                        mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                    }
                    if (mySortedMap != null && !mySortedMap.isEmpty()) {
                        currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                    }
                }
            } catch( ClassNotFoundException e ) {
                //my class isn't there!
                Log.i (TAG, "Class not found: android.app.usage.UsageStatsManager");
            }
        } else {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
            currentApp = tasks.get(0).processName;
        }

        Log.i("Foreground App", "getForegroundApp: " + currentApp);
        return currentApp;
    }

AlertDialog

##  

  

        AlertDialog.Builder builder = null;
        if (ThemeUtil.getCurrentTheme() == THEME_LIGHT) {
            builder = new AlertDialog.Builder(view.getContext(), R.style.LightDialogTheme);
        } else if (ThemeUtil.getCurrentTheme() == THEME_DARK) {
            builder = new AlertDialog.Builder(view.getContext(), R.style.DarkDialogTheme);
        }
        builder.setTitle(getString(R.string.my_download_delete_title));
        builder.setMessage(getString(R.string.my_download_delete_body));
        
        //確認按鈕
        builder.setPositiveButton(getString(R.string.my_confirm), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                deleteAction(); //刪除檔案
            }
        });
        
       //取消按鈕
       builder.setNegativeButton(getString(R.string.my_cancel), new DialogInterface.OnClickListener() {
        
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //nothing to do
            }
        
        }).create();
        
        final AlertDialog dialog = builder.create();
        //2. now setup to change color of the button
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface arg0) {
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.yellow));
                dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.red));
            }
        });
        
        dialog.show();

Broken image

img{
    position: relative; /*pildi asukoht peab olema relatiivne, et loodav ikoon selle kinni kataks*/
    display: inline-block;
    font-size: 1rem;
    text-align: center;
    text-transform: uppercase;
}
/* Paigutab elemendi järel */
img::after{
    position: absolute; /*absoluut positisoon on vajalik, et katta kinni see katkise pildi ikoon*/
    top: 0;
    left: 0;
    width: 100%;
    min-width: 200px;
    padding: 10px 20px 10px 45px;
    border: dashed 1px #888;
    background-color: #f0f0f0;
    background-image: url(no_camera.png);
    background-size: 10%;
    background-repeat: no-repeat;
    background-position: 10px;
    z-index: 1;
    content: "" attr(alt) " Not found"; /*võtab alt atribuudi ning paneb lõppu not found*/
}

Broken image

img{
    position: relative; /*pildi asukoht peab olema relatiivne, et loodav ikoon selle kinni kataks*/
    display: inline-block;
    font-size: 1rem;
    text-align: center;
    text-transform: uppercase;
}
/* Paigutab elemendi järel */
img::after{
    position: absolute; /*absoluut positisoon on vajalik, et katta kinni see katkise pildi ikoon*/
    top: 0;
    left: 0;
    width: 100%;
    min-width: 200px;
    padding: 10px 20px 10px 45px;
    border: dashed 1px #888;
    background-color: #f0f0f0;
    background-image: url(no_camera.png);
    background-size: 10%;
    background-repeat: no-repeat;
    background-position: 10px;
    z-index: 1;
    content: "" attr(alt) " Not found"; /*võtab alt atribuudi ning paneb lõppu not found*/
}

Gravity Perks // GP Limit Submissions // Dynamically Set Limit

Gravity Perks // GP Limit Submissions // Dynamically Set Limit
<?php
/**
 * Gravity Perks // GP Limit Submissions // Dynamically Set Limit
 * http://gravitywiz.com/gravity-forms-limit-submissions/
 */
add_filter( 'gpls_rule_groups', function( $rule_groups ) {

	foreach( $rule_groups as &$rule_group ) {
		if( $rule_group->name == 'Your Feed Name' ) {
			$rule_group->limit = 100;
		}
	}

	return $rule_groups;
} );

HE Journey

#include<bits/stdc++.h>
using namespace std;

// #DynamicProgramming
// https://www.hackerearth.com/problem/algorithm/journey-1-0418ba3e/

int minCost(int n, vector<int> li, vector<int> ci, vector<int> pi, int x);
int solve(vector<int> li, vector<int> ci, vector<int> pi, int x, int start, int end, int cost);
int mini(int a, int b);

int main(){
    int n,m;
    cin>>n>>m;
    vector<int> li(n-1);
    vector<int> ci(n-1);
    vector<int> pi(n-1);
    for(int i=0;i<n-1;i++){
        cin>>li[i];
    }
    for(int i=0;i<n-1;i++){
        cin>>ci[i];
    }
    for(int i=0;i<n-1;i++){
        cin>>pi[i];
    }
    while(m--){
        int x;
        cin>>x;
        cout<<minCost(n,li,ci,pi,x)<<endl;
    }
    
    return 0;
}

int mini(int a, int b){
    if(a<b){
        return a;
    }else{
        return b;
    }
}

int solve(vector<int> li, vector<int> ci, vector<int> pi, int charge, int start, int end, int cost){
    if(charge<0){
        return -1;  // if charge is depleted even before reaching the city
    }
    if(charge<li[start]){
        if(ci[start]<li[start]){   // if both charge & battery at shop are not enough to go to next city
            return -1;
        }
    }
    if(start==(end-1)){ // at last-but-one city
        if(charge<li[start]){   // if current charge is less than that is req to travel to last city
            //charge=ci[start]-li[start]; // replace battery
            return cost+pi[start];  // buy the battery and move forward
        }else{
            //charge-=li[start];
            return cost;    // journey possible without buying battery
        }
    }
    int with,without;
    without=solve(li,ci,pi,charge-li[start],start+1,end,cost);
    with=solve(li,ci,pi,ci[start]-li[start],start+1,end,cost+pi[start]);
    if(without!=-1){   // if journey can be completed without buying battery at current city
        return mini(with,without);
    }else{
        if(with!=-1){
            return with;    // if journey can be completed only if battery is bought at current city
        }else{
            return -1;    // if journey can't be completed even after buying
        }
    }
    
    
    
}
int minCost(int n,vector<int> li,vector<int> ci,vector<int> pi,int x){
    return solve(li,ci,pi,x,0,n-1,0);
}

24

UMS Email Password Change 24
# app/models.py
# ...
class User(UserMixin, db.Model):
    # ...
    def email_change(self, token):
        s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token.encode('utf-8'))
        except:
            return False
        user = User.query.get(data.get('change_email'))
        new_email = data.get('new_email')
        if user is None:
            return False
        if new_email is None:
            return False
        if self.query.filter_by(email=new_email).first() is not None:
            return False
        self.email = new_email
        db.session.add(self)
        return True

23

UMS Email Password Change 22
# tests/test_user_model.py
# ...
class BasicTestCase(unittest.TestCase):
    # ...
    def test_email_change(self):
        u = User(email='john@example.com', username='john', password='cat')
        db.session.add(u)
        db.session.commit()

        token = u.generate_email_change_token('john@example.com')
        self.assertFalse(u.email_change(token))

        token = u.generate_email_change_token('mary@example.com')
        self.assertTrue(u.email_change(token))
        self.assertEqual(u.email, 'mary@example.com')
        self.assertNotEqual(u.email, 'john@example.com')

        token = u.generate_email_change_token(None)
        self.assertFalse(u.email_change(token))

        token = u.generate_email_change_token('john@example.com')
        db.session.delete(u)
        db.session.commit()
        self.assertFalse(u.email_change(token))

22

UMS Email Password Reset 22
# app/models.py
# ...
class User(UserMixin, db.Model):
    # ...
    def generate_email_change_token(self, new_email, expiration=3600):
        s = JSONWebSignatureSerializer(current_app.config['SECRET_KEY'])
        return s.dumps({'change_email': self.id,
                        'new_email': new_email}).decode('utf-8')

21

UMS Email Password Change 21
# tests/test_user_model.py
# ...
class BasicTestCase(unittest.TestCase):
    # ...
    def test_generate_email_change_token(self):
        u = User(email='john@example.com', username='john', password='cat')
        db.session.add(u)
        token = u.generate_email_change_token('mary@example.com')
        self.assertTrue(token is not None)

20

UMS Email Password Reset 20
{# app/templates/auth/password_reset.html #}

{% extends "base.html" %}
{% import 'bootstrap/wtf.html' as wtf%}

{% block page_content %}
<h1>Enter new password.</h1>

{{ wtf.quick_form(form) }}
{% endblock %}

19

UMS Email Password Reset 19
# app/auth_blueprint/views.py
# ...
from .forms import PasswordResetForm()
# ...
@auth.route('/password_reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
    form = PasswordResetForm()
    if not current_user.is_anonymous:
        flash('You are already logged in. ' +
              'You do not need to request a new password.',
              'warning')
        return redirect(url_for('main.index'))
    if form.validate_on_submit():
        if User.password_reset(token, form.newpassword.data):
            db.session.commit()
            flash('Your password has been updated. Please log in.', 'success')
            return redirect(url_for('auth.login'))
        else:
            flash('Invalid confirmation token. ' +
                  'Your token has either expired or is invalid.',
                  'danger')
            return redirect(url_for('auth.login'))
    for field, errors in form.errors.items():
        for error in errors:
            flash(u"Error in the %s field - %s" % (
                getattr(form, field).label.text,
                error
            ), 'danger')
    return render_template('auth/password_reset.html', form=form)

18

UMS Email Password Reset 18
# app/auth_blueprint/forms.py
# ...
class PasswordResetForm(FlaskForm):
    newpassword = PasswordField('New Password',
                                validators=[DataRequired(),
                                            EqualTo('newpassword2')])
    newpassword2 = PasswordField('Repeat New Password',
                                 validators=[DataRequired()])
    submit = SubmitField('Reset Password')