branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>bbenskye/MyViews<file_sep>/app/src/main/java/com/example/wenchao/myapplication/views/MyTextView.java package com.example.wenchao.myapplication.views; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.wenchao.myapplication.R; /** * Created on 2016/9/7. * * @author wenchao * @since 1.0 */ public class MyTextView extends RelativeLayout { private Context context; private TextView tv; private EditText edt; public static final int TYPE_NUMBER = 0; public static final int TYPE_TEXT = 1; public static final int TYPE_PHONE = 2; public MyTextView(Context context, String title, int type) { super(context); this.context = context; initView(title, type); } // public MyTextView(Context context, AttributeSet attrs) { // super(context, attrs); // context = context; // } private void initView(String title, int type) { View.inflate(context, R.layout.view_text, this); tv = (TextView) findViewById(R.id.tv_title); edt = (EditText) findViewById(R.id.tv_content); tv.setText(title); switch (type) { case TYPE_NUMBER: edt.setInputType(EditorInfo.TYPE_CLASS_NUMBER); break; case TYPE_PHONE: edt.setInputType(EditorInfo.TYPE_CLASS_PHONE); break; case TYPE_TEXT: edt.setInputType(EditorInfo.TYPE_CLASS_TEXT); break; } } public String getTypedContent() { return edt.getText().toString(); } } <file_sep>/app/src/main/java/com/example/wenchao/myapplication/VideoRecorderActivity.java package com.example.wenchao.myapplication; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.hardware.Camera; import android.media.MediaRecorder; import android.os.Bundle; import android.view.Gravity; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ProgressBar; import android.widget.Toast; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; /** * Created on 2016/9/14. * * @author wenchao * @since 1.0 */ public class VideoRecorderActivity extends Activity implements SurfaceHolder.Callback, View.OnClickListener, MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener { private SurfaceView surfaceView; private SurfaceHolder holder; private Camera mCamera; private MediaRecorder mediarecorder; private Button btn_start, btn_pause, btn_stop, btn_ptr; private ProgressBar mProgress; private Timer mTimer; private int mTimeCount; private static boolean isstop = false; WindowManager.LayoutParams wmParams; WindowManager wm; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_videorecorder); initView(); } private void initView() { // final Button button = new Button(getApplicationContext()); // wm = (WindowManager) getApplicationContext() // .getSystemService(Context.WINDOW_SERVICE); // wmParams = new WindowManager.LayoutParams(); // // /** // * 以下都是WindowManager.LayoutParams的相关属性 具体用途请参考SDK文档 // */ // wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // 这里是关键,你也可以试试2003 //// wmParams.type = WindowManager.LayoutParams.TYPE_PHONE; // 这里是关键,你也可以试试2003 // wmParams.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明 // /** // * 这里的flags也很关键 代码实际是wmParams.flags |= FLAG_NOT_FOCUSABLE; // * 40的由来是wmParams的默认属性(32)+ FLAG_NOT_FOCUSABLE(8) // */ // wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE // | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; // wmParams.width = 5; // wmParams.height = 5; // wmParams.gravity= Gravity.LEFT|Gravity.TOP; // wmParams.x = 0; // wmParams.y = 0; // // // 设置悬浮窗的Touch监听 // button.setOnTouchListener(new View.OnTouchListener() { // int lastX, lastY; // int paramX, paramY; // // public boolean onTouch(View v, MotionEvent event) { // switch(event.getAction()) { // case MotionEvent.ACTION_DOWN: // lastX = (int) event.getRawX(); // lastY = (int) event.getRawY(); // paramX = wmParams.x; // paramY = wmParams.y; // break; // case MotionEvent.ACTION_MOVE: // int dx = (int) event.getRawX() - lastX; // int dy = (int) event.getRawY() - lastY; // wmParams.x = paramX + dx; // wmParams.y = paramY + dy; // // 更新悬浮窗位置 // wm.updateViewLayout(button, wmParams); // break; // } // return true; // } // }); // wm.addView(button, wmParams); // 创建View surfaceView = (SurfaceView) findViewById(R.id.surface_view_video); btn_start = (Button) findViewById(R.id.push_to_recorder); btn_stop = (Button) findViewById(R.id.stop_to_recorder); btn_pause = (Button) findViewById(R.id.pause_to_recorder); btn_ptr = (Button) findViewById(R.id.btn_start); mProgress = (ProgressBar) findViewById(R.id.progressBar); mProgress.setMax(10); btn_start.setOnClickListener(this); btn_stop.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_ptr.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: startRecord(); // Toast.makeText(VideoRecorderActivity.this, "down", Toast.LENGTH_SHORT).show(); break; case MotionEvent.ACTION_UP: if (!isstop) stop(); // Toast.makeText(VideoRecorderActivity.this, "up", Toast.LENGTH_SHORT).show(); break; } return false; } }); holder = surfaceView.getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void surfaceCreated(SurfaceHolder holder) { this.holder = holder; try { initCamera(); } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { this.holder = holder; } @Override public void surfaceDestroyed(SurfaceHolder holder) { this.holder = holder; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.push_to_recorder: startRecord(); break; case R.id.pause_to_recorder: break; case R.id.stop_to_recorder: stop(); Toast.makeText(VideoRecorderActivity.this, "stop!", Toast.LENGTH_SHORT).show(); break; } } private void stop() { isstop = true; mProgress.setProgress(0); if (mTimer != null) { mTimer.cancel(); } if (mediarecorder != null) { // 停止录制 mediarecorder.stop(); // 释放资源 mediarecorder.release(); mediarecorder = null; freeCameraResource(); } Intent i = new Intent(this, VideoPlayActivity.class); startActivity(i); } private void startRecord() { isstop = false; mediarecorder = new MediaRecorder();// 创建mediarecorder对象 mediarecorder.reset(); if (mCamera != null) mediarecorder.setCamera(mCamera); // 设置录制视频源为Camera(相机) mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediarecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4 mediarecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); // 设置录制的视频编码mp4 mediarecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); mediarecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mediarecorder.setOrientationHint(90); // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错 mediarecorder.setVideoSize(176, 144); // mediarecorder.setVideoSize(240, 180); // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错 mediarecorder.setVideoFrameRate(30); mediarecorder.setPreviewDisplay(holder.getSurface()); // 设置视频文件输出的路径 mediarecorder.setOutputFile("/sdcard/love1.mp4"); try { // 准备录制 mediarecorder.prepare(); // mediarecorder.setOnErrorListener(this); // mediarecorder.setOnInfoListener(this); System.out.println("start!!!!!!!!!!"); // 开始录制 mediarecorder.start(); System.out.println("start!!!!!!!!!!"); } catch (IllegalStateException e) { // TODO Auto-generated catch block System.out.println("illeg!!!!!!!!!!"); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Toast.makeText(VideoRecorderActivity.this, "start!", Toast.LENGTH_SHORT).show(); mTimeCount = 0;// 时间计数器重新赋值 mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub mTimeCount++; mProgress.setProgress(mTimeCount);// 设置进度条 if (mTimeCount == 10) {// 达到指定时间,停止拍摄 stop(); // if (mOnRecordFinishListener != null) // mOnRecordFinishListener.onRecordFinish(); } } }, 0, 1000); } /** * 初始化摄像头 * * @throws IOException * @author wen * @date 2015-3-16 */ private void initCamera() throws IOException { if (mCamera != null) { freeCameraResource(); } try { mCamera = Camera.open(); } catch (Exception e) { e.printStackTrace(); freeCameraResource(); } if (mCamera == null) return; setCameraParams(); mCamera.setDisplayOrientation(90); mCamera.setPreviewDisplay(holder); mCamera.startPreview(); mCamera.unlock(); } /** * 设置摄像头为竖屏 * * @author wen * @date 2015-3-16 */ private void setCameraParams() { if (mCamera != null) { Camera.Parameters params = mCamera.getParameters(); params.set("orientation", "portrait"); mCamera.setParameters(params); } } /** * 释放摄像头资源 * * @author liuyinjun * @date 2015-2-5 */ private void freeCameraResource() { if (mCamera != null) { mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.lock(); mCamera.release(); mCamera = null; } } @Override public void onError(MediaRecorder mr, int what, int extra) { System.out.println("error!!!!!!!!!!"); } @Override public void onInfo(MediaRecorder mr, int what, int extra) { System.out.println("onInfo!!!!!!!!!!"); } } <file_sep>/app/src/main/java/com/example/wenchao/myapplication/MainActivity.java package com.example.wenchao.myapplication; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.Toast; import com.example.wenchao.myapplication.utils.ListDataSave; import com.example.wenchao.myapplication.views.MyCheckBox; import com.example.wenchao.myapplication.views.MyRadioGroup; import com.example.wenchao.myapplication.views.MyTextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Button mBtn; String pack = "com.example.wenchao.myapplication4"; private int i = 3; private MyTextView myTextView; private MyRadioGroup myRadioGroup; private MyCheckBox myCheckBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_main); final ScrollView scrollView = new ScrollView(this); scrollView.setLayoutParams(new RelativeLayout .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); final LinearLayout layout2 = new LinearLayout(this); layout2.setOrientation(LinearLayout.VERTICAL); Button btn1 = new Button(this); Button btn2 = new Button(this); Button btn3 = new Button(this); Button btn4 = new Button(this); Button btn5 = new Button(this); //创建输入框 myTextView = new MyTextView(MainActivity.this, "说出一个三国人物:", MyTextView.TYPE_TEXT); String[] checkItems = {"刘备", "关羽", "张飞", "赵云", "马超", "黄忠", "曹孟德", "张辽", "张郃", "徐晃", "乐进", "于禁", "孙权", "太史子义", "甘宁", "周泰", "蒋钦", "凌统"}; List<String> itemsList = new ArrayList<>(); for (String str : checkItems) { itemsList.add(str); } //创建多选框 myCheckBox = new MyCheckBox(this, "属同一势力的有:", itemsList); myCheckBox.requestFocus(); List<String> radioItems = new ArrayList<>(); radioItems.add("魏"); radioItems.add("蜀"); radioItems.add("吴"); radioItems.add("群雄"); //创建单选框 myRadioGroup = new MyRadioGroup(this, "所属势力:", radioItems); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(20, 10, 10, 10); // lp.leftMargin = 10; myCheckBox.setLayoutParams(lp); // setContentView(layout2); btn1.setText("添加view"); btn2.setText("提交"); btn3.setText("拍照"); btn4.setText("小视频"); btn5.setText("sharepreference"); layout2.addView(myTextView); layout2.addView(myRadioGroup, lp); layout2.addView(myCheckBox); layout2.addView(btn2, lp); layout2.addView(btn3, lp); layout2.addView(btn4, lp); layout2.addView(btn1, lp); layout2.addView(btn5, lp); scrollView.addView(layout2); setContentView(scrollView); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "btn1 clicked!", Toast.LENGTH_SHORT).show(); RelativeLayout relativeLayout = new RelativeLayout(v.getContext()); RelativeLayout.LayoutParams params = new RelativeLayout .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); if (i % 2 == 0) { params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } else { params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); } Button btn_x = new Button(v.getContext()); btn_x.setText("Button" + i); relativeLayout.addView(btn_x, params); layout2.addView(relativeLayout); scrollView.fullScroll(ScrollView.FOCUS_DOWN); i++; } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { StringBuilder sb = new StringBuilder(); String edtContent = myTextView.getTypedContent(); sb.append(edtContent + " \n\n"); String radio = myRadioGroup.getCheckedResult(); sb.append(radio + ": \n"); List<String> result = myCheckBox.getCheckedResult(); for (String str : result) { sb.append(str); sb.append(", "); } if (!TextUtils.isEmpty(edtContent) || !TextUtils.isEmpty(radio) || result.size() > 0) { String res = sb.toString().substring(0, sb.length() - 1); Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show(); System.out.println("Checked : " + res); } else { Toast.makeText(MainActivity.this, "请做出一个选择", Toast.LENGTH_SHORT).show(); } } }); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, VideoRecorderActivity.class); startActivity(i); } }); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, TakePictureActivity.class); startActivity(i); } }); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<String> datas = new ArrayList<String>(); for (int i = 0; i < 10; i++) { datas.add("string-" + i); } ListDataSave datasave = new ListDataSave(MainActivity.this, "myview"); datasave.setDataList("tag", datas); List<String> newMyList = datasave.getDataList("tag"); for (String str : newMyList) { Log.i("myView", "str = " + str); } } }); } } <file_sep>/app/src/main/java/com/example/wenchao/myapplication/MyRecyclerAdapter.java package com.example.wenchao.myapplication; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; /** * Created on 2016/9/22. * * @author wenchao * @since 1.0 */ public class MyRecyclerAdapter extends RecyclerView.Adapter { private List<String> mData; private Context context; private LayoutInflater inflater; private OnMyItemClickedListener clickedListener; public MyRecyclerAdapter(Context context, List<String> data){ this.context = context; this.mData = data; inflater = LayoutInflater.from(context); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.recycle_item, parent, false); MyViewHolder holder = new MyViewHolder(view); return holder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ((MyViewHolder)holder).tv.setText(mData.get(position)); if (clickedListener != null){ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clickedListener.onClick(position); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { clickedListener.onLongClick(position); return true; } }); } } @Override public int getItemCount() { return mData.size(); } class MyViewHolder extends RecyclerView.ViewHolder { public TextView tv; public MyViewHolder(View view){ super(view); this.tv = (TextView) view.findViewById(R.id.tv_item_recycler); } } public void setClickedListener(OnMyItemClickedListener listener){ this.clickedListener = listener; } public interface OnMyItemClickedListener{ void onClick(int position); void onLongClick(int position); } }
64daf9ae13967bb36ad2f5f4bc2d9bb6451fb608
[ "Java" ]
4
Java
bbenskye/MyViews
fd2a95b8ac2777dcf01b0db4738efde28cafc1c9
67f3168240cc967e847aaf3877e9e20c63a6ffe3
refs/heads/master
<repo_name>toxAndreev/basic-js<file_sep>/src/recursive-depth.js module.exports = class DepthCalculator { calculateDepth(arr) { if (Array.isArray(arr)) { let depth = 1; let max = 1; for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) depth = this.calculateDepth(arr[i]) + 1; max = max < depth ? depth : max; } return max; } return 1; } };
ba4dbf6391d38959fc60fd0b4d3f333fd520d5fd
[ "JavaScript" ]
1
JavaScript
toxAndreev/basic-js
d7bdbe0f7edb533ab954b3f2368343cadf3f0c7e
30862b6f833f43280c5ea61333cec54d5f6e5980
refs/heads/main
<file_sep>asgiref==3.3.4 Django==3.2.1 django-active-link==0.1.8 django-widget-tweaks==1.4.8 Pillow==8.2.0 pytz==2021.1 sqlparse==0.4.1 typing-extensions==3.10.0.0 <file_sep># Generated by Django 3.1.3 on 2021-03-24 10:19 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PriceWash', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('car_type', models.CharField(choices=[('D', '--------'), ('T', 'Trucks'), ('MSM', 'Medium size machines'), ('C', 'Cars')], default='C', max_length=100, verbose_name='Type cars')), ('wash_type', models.CharField(choices=[('D', '--------'), ('TW', 'Thorough washing'), ('WWST', 'Washing with a special tool'), ('ON', 'Only Karcher'), ('EW', 'Engine wash'), ('DTH', 'Darken the balloon')], default='TW', max_length=100, verbose_name='Enter wash type')), ('price', models.FloatField(default=0)), ], ), ] <file_sep>from django.contrib import admin from django.db import models from .models import PriceWash # Register your models here. @admin.register(PriceWash) class PriceWashAdmin(admin.ModelAdmin): list_display = ( 'car_type', 'wash_type', 'price' ) list_display_links = ( 'car_type', 'wash_type', 'price' ) list_filter = ( 'car_type', 'wash_type' ) <file_sep># Carwash Car Wash prog sfsfsdf <file_sep>from django.views.generic import TemplateView, CreateView, DetailView from .models import Car ,Worker from payment.models import PriceWash from django.utils import timezone from django.db.models import Sum class CarsView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(CarsView, self).get_context_data(**kwargs) startdate = self.request.GET.get('startdate', None) enddate = self.request.GET.get('enddate', None) car_type = self.request.GET.get('cartype', 'all') worker = self.request.GET.get('worker', 'all') print(car_type) carwash = Car.objects.all().order_by('-id') if startdate and enddate: carwash = carwash.filter(created__range=[startdate + ' 00:00', enddate +' 23:59']) context['count_date'] = carwash.count() context['price_date'] = carwash.filter().aggregate(Sum('price')) if car_type != 'all': carwash = carwash.filter(car_type=car_type) context['count_type'] = carwash.count() context['price_type'] = carwash.filter().aggregate(Sum('price')) if worker != 'all': carwash = carwash.filter(worker__full_name=worker) context['count'] = carwash.count() context['price'] = carwash.filter().aggregate(Sum('price')) context['count_all'] = carwash.count() context['price_all'] = carwash.filter().aggregate(Sum('price')) context['cars'] = carwash context['startdate'] = startdate context['enddate'] = enddate context['select_car_type'] = car_type context['select_worker'] = worker context['worker_list'] = Worker.objects.all() context['client'] = Car.objects.all() return context class AddCarsView(CreateView): template_name = 'add_car.html' model = Car fields = ['worker', 'car_type', 'wash_type', 'model', 'number', 'price' ] success_url = '/cars/' def get_context_data(self, **kwargs): context = super(AddCarsView, self).get_context_data(**kwargs) context['price_list'] = PriceWash.objects.all() return context def form_valid(self, form): form.instance.user= self.request.user return super(AddCarsView, self).form_valid(form) class WorkerView(TemplateView): template_name = 'worker.html' def get_context_data(self, **kwargs): context = super(WorkerView, self).get_context_data(**kwargs) context['workers'] = Worker.objects.all() return context class CarsDetailView(DetailView): template_name = 'c_detail.html' model = Car context_object_name = 'cars' <file_sep># Generated by Django 3.1.3 on 2021-03-24 10:19 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Worker', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('full_name', models.CharField(max_length=100, verbose_name='Full name Worker')), ('started_work', models.DateField(auto_now_add=True)), ('phone', models.CharField(max_length=100, verbose_name='Phone')), ('status', models.CharField(choices=[('B', 'Busy'), ('OOW', 'Out-of-work')], default='OOW', max_length=100, verbose_name='Status worker')), ], ), migrations.CreateModel( name='Car', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('car_type', models.CharField(choices=[('D', '--------'), ('T', 'Trucks'), ('MSM', 'Medium size machines'), ('C', 'Cars')], default='D', max_length=100, verbose_name='Type cars')), ('wash_type', models.CharField(choices=[('D', '--------'), ('TW', 'Thorough washing'), ('WWST', 'Washing with a special tool'), ('ON', 'Only Karcher'), ('EW', 'Engine wash'), ('DTH', 'Darken the balloon')], default='D', max_length=100, verbose_name='Enter wash type')), ('model', models.CharField(max_length=100, verbose_name='Model cars')), ('number', models.CharField(max_length=100, verbose_name='Number cars')), ('price', models.FloatField(default=0)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('worker', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='main.worker')), ], ), ] <file_sep>from django.shortcuts import render from django.views.generic import TemplateView class CarwashPayView(TemplateView): pass<file_sep>from django.shortcuts import render from django.views.generic import TemplateView, ListView from django.contrib.auth import authenticate, login from .forms import LoginForm from django.shortcuts import redirect from django.urls import reverse from django.http import HttpResponse # Create your views here. class BaseView(TemplateView): template_name = 'base.html' def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['salom'] = '<NAME>' return context class LoginView(TemplateView): template_name = 'registration/login.html' def get_context_data(self, **kwargs): context = super(LoginView, self).get_context_data(**kwargs) context['form'] = LoginForm() return context def post(self, request): form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['<PASSWORD>']) if user is not None: if user.is_active: login(request, user) if 'back_url' in request.POST: return redirect(request.POST['back_url']) return redirect(reverse('base')) else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login')<file_sep>WASH_TYPE = [ ('D', '--------'), ('TW','Thorough washing'), ('WWST','Washing with a special tool'), ('ON', 'Only Karcher'), ('EW','Engine wash'), ('DTH','Darken the balloon'), ] CARS_TYPE = [ ('D', '--------'), ('T', 'Trucks'), ('MSM', 'Medium size machines'), ('C', 'Cars'), ] WORKER_STATUS = [ ('B', 'Busy'), ('OOW','Out-of-work'), ]<file_sep>from django.contrib import admin from .models import Worker, Car # Register your models here. @admin.register(Worker) class WorkerAdmin(admin.ModelAdmin): pass @admin.register(Car) class CarAdmin(admin.ModelAdmin): list_display = ( 'worker', 'car_type', 'wash_type', 'model', 'number', 'user' ) list_display_links = ( 'worker', 'car_type', 'wash_type', 'model', 'number', 'user' ) list_filter = ( 'worker', 'car_type', 'wash_type', 'model' ) <file_sep>from django.db import models from main.choices import WASH_TYPE, CARS_TYPE class PriceWash(models.Model): car_type = models.CharField('Type cars', choices=CARS_TYPE, default='C', max_length=100) wash_type = models.CharField('Enter wash type', choices=WASH_TYPE, default='TW', max_length=100) price = models.FloatField(default=0) def __str__(self): return str(self.car_type) <file_sep>from django.db import models from .choices import WASH_TYPE ,CARS_TYPE, WORKER_STATUS from django.contrib.auth.models import User class Worker(models.Model): full_name = models.CharField('Full name Worker', max_length=100) started_work = models.DateField(auto_now_add=True) phone = models.CharField('Phone', max_length=100) status = models.CharField('Status worker', choices=WORKER_STATUS, default='OOW', max_length=100 ) def __str__(self): return self.full_name class Car(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) worker = models.ForeignKey(Worker, related_name='+', on_delete=models.CASCADE) car_type = models.CharField('Type cars', choices=CARS_TYPE, default='D', max_length=100) wash_type = models.CharField('Enter wash type', choices=WASH_TYPE, default='D', max_length=100) model = models.CharField('Model cars', max_length=100) number = models.CharField('Number cars', max_length=100 ) price = models.FloatField(default=0) def __str__(self): return self.model <file_sep>from django import template register = template.Library() @register.filter(name='to_int') def to_int(val): try: return int(val) except: return val<file_sep>from django.urls import path from .views import CarsView, WorkerView, AddCarsView, CarsDetailView urlpatterns = [ path('cars/', CarsView.as_view(), name='car'), path('workers', WorkerView.as_view(), name='worker'), path('cars/add', AddCarsView.as_view(), name='add_car'), path('car/detail/<int:pk>/', CarsDetailView.as_view(), name='car_detail'), ] <file_sep>from django.contrib import admin from django.urls import path from .views import BaseView from main.views import CarsView from .views import BaseView, LoginView urlpatterns = [ path('', CarsView.as_view(), name='base'), path('login/', LoginView.as_view(), name='login-view'), ]
06a9d247e470a3a6900b40b5484357e846e2ea36
[ "Markdown", "Python", "Text" ]
15
Text
Saidazimxonn/Carwash
8e2dbe3f597d67c7514c63bd6df9ca9186b0efe6
42ab8ae924d85bc12ff0d432bc1434a8579f5970
refs/heads/master
<file_sep>package com.zhuxt.test; /** * Created by Administrator on 2015/11/15. */ public interface DisplayElement { public void display(); }
b24de7975699f4773b155044bb2391d124af049d
[ "Java" ]
1
Java
zhuxt2015/ObserverPattern
940f578a02624f96b8653e08ed468484e1b63c4e
c870b4e875df9bfdfa57765f12969c531a8d0b58
refs/heads/master
<repo_name>victorborja/ng-base<file_sep>/src/angular/decorators.js import _ from 'lodash'; import angular from 'angular'; import {componentView} from 'config/loaders'; function registerService(mod, Target) { function service(...args) { return new Target(...args); } const serviceName = Target.$service.name; const deps = _.flatten([ Target.$inject || [], [service] ]); mod.factory(serviceName, deps); } function registerController(mod, target) { mod.controller(target.$controller.name, target); } function registerFilter(mod, Target) { function filter(...args) { const instance = new Target(...args); return instance.filter.bind(instance); } const filterName = Target.$filter.name; const deps = _.flatten([ Target.$inject || [], [filter] ]); mod.filter(filterName, deps); } function registerComponent(mod, target) { const elementName = target.$component.elementName || _.kebabCase(target.$component.name); const directiveName = target.$component.directiveName || _.camelCase(target.$component.name); const controllerName = target.$component.controllerName || `${directiveName}Ctrl`; const view = target.$component.view || `${elementName}/${elementName}`; const template = target.$component.template || componentView(view); mod.controller(controllerName, target); mod.directive(directiveName, function directive() { return { restrict: 'E', template: template, controller: controllerName, controllerAs: target.$component.controllerAs || directiveName, scope: target.$component.scope || {} }; }); } function registerComponentRoute(mod, target) { mod.config(['$stateProvider', function config($stateProvider) { const elementName = target.$component.elementName || _.kebabCase(target.$component.name); const template = `<${elementName}></${elementName}>`; $stateProvider.state(target.$route.name, _.merge({ template: template }, target.$route)); }]); } function namedDecorator(type) { return function named(name, options) { function decorator(target) { target[type] = _.merge({ name: name || target.name }, options || {}); return target; } if (typeof name === 'function') { const target = name; const targetName = target.name; return named(targetName, options)(target); } return decorator; }; } const filter = namedDecorator('$filter'); const service = namedDecorator('$service'); const controller = namedDecorator('$controller'); const component = namedDecorator('$component'); export { angular, filter, service, controller, component }; export function module(...args) { return function decorator(target) { const mod = angular.module(...args); if (target.$component) { registerComponent(mod, target); if (target.$route) { registerComponentRoute(mod, target); } } else if (target.$service) { registerService(mod, target); } else if (target.$filter) { registerFilter(mod, target); } else if (target.$controller) { registerController(mod, target); } return target; }; } export function inject(...deps) { return function decorator(target) { target.$inject = deps; }; } export function route(name, url, options) { return function decorator(target) { target.$route = _.merge({ name: name, url: url }, options || {}); }; } <file_sep>/README.md # ng-base This project is just a dead simple angular node tools ready for development. It includes: - angular/decorators [Decorators](#decorators) for declaring components using es6 classes. All components are declared at `src/index.js` A component like `n-app` would include these: - `n-app.js` The component implementation file. - `n-app.html` Optional template. Unless specified via the `template` or `templateUrl` options for `@component`. - `n-app.scss` Optional styles for this component. - sass All `.scss` get compiled into `.css` - es6 Compiles `src/*.js` using babel. - webpack Creates js/css bundles for optimized asset delivery. - watch Just edit and files get automatically recompiled. - browsersync Reloads connected browsers when new bundle is built. ## prerequisites - `npm install` ## development `npm run dev` ## Decorators ```javascript @module('n') @component('n-app') @inject('$scope') class AppComponent { constructor($scope) { // ... } } ``` - `@module` Defines the unleraying component as part of the specified module. You can create the module immediatly by using providing module dependencies: `@module('n', [])`. - `@inject` Decorates the component with its arguments as the `$inject` property. - `@component` Declares the tag name used for this component. Note that the name is dashed instead of camel cased. Options: Any [directive](https://docs.angularjs.org/guide/directive) options. As a convention the `n-app` component will have its template in the file `n-app/n-app.html`. Unless the `template` or `templateUrl` options are given. Additionally a `view` option can override the default path under `components` to look for the template. This can be used for example to define nested components like: ```javascript @module('n') @component('n-app-toolbar', { view: 'n-app/toolbar' }) class AppToolbarComponent { } ``` By default, components have isolated scopes. Their controller is aliased as the camelCased component name. `nAppToolbar` for the previous example. You can provide the `scope` option to `@component` as you would for an element directive. - `@route` Makes the component to handle certain [route](https://github.com/angular-ui/ui-router). `@route(STATE_NAME, PATH, [OPTIONS])` ```javascript @module('n') @component('n-welcome') @route('index', '/') class WelcomeController { } ``` ## resources - [angular 1.4](http://angularjs.org) - [angular/decorators](https://github.com/victorborja/ng-base/blob/master/src/angular/decorators.js) <file_sep>/src/components/n-app/n-app.js import {module, component, inject} from 'angular/decorators'; @module('n') @component('n-app') @inject('$scope') export class AppComponent { constructor($scope) { $scope.counter = 0; $scope.increment = () => $scope.counter ++; $scope.decrement = () => $scope.counter --; } }
b15f635b5d8be9cf164dec67d22e2f98fd538a4f
[ "JavaScript", "Markdown" ]
3
JavaScript
victorborja/ng-base
e43c3720c55ca6092336f58efe540daff3f1bf7a
4dcde33f5b36717903d5137e793219aa87054787
refs/heads/master
<repo_name>peterwilletts24/INCOMPASS_Forecast_Website_JASMIN<file_sep>/INCOMPASS_2015_Copy_UM_Plots_WServer.bash #!/bin/bash _args="-a --ignore-existing" latest_forecast_dir="/nfs/see-fs-01_users/eepdw/public_html/INCOMPASS_2015/Images/Latest_Forecast/" analysis_dir="/nfs/see-fs-01_users/eepdw/public_html/INCOMPASS_2015/Images/Analysis/" ftp_dir='/nfs/a132/js08rgjf/incompass/' rm $latest_forecast_dir*.png last_dir=$(ls -rX $ftp_dir --ignore '*06Z' --ignore '*18Z*' | head -1) # Latest Forecast files=$(ls $ftp_dir$last_dir/*.png) for f in $files do if [ -f "$f" ] then rsync $_args "$f" "$latest_forecast_dir" else echo "Error $f file not found." fi done chmod 777 $latest_forecast_dir*.png # Analysis an_f=$(ls -t $ftp_dir/*/*_T+0_*.png) for f in $an_f do if [ -f "$f" ] then rsync $_args "$f" "$analysis_dir" else echo "Error $f file not found." fi done chmod 777 $analysis_dir*.png /apps/canopy-1.5.2/bin/python /nfs/see-fs-01_users/eepdw/python_scripts/INCOMPASS_2015_Website/INCOMPASS_Jinja_Insert_Vars_gen_HTML.py <file_sep>/INCOMPASS_Gen_html_fdirs_all_regions.py import glob import numpy as np import re import os import commands #from flask import Flask #app = Flask(__name__) import pdb # Directories where forecast plots are - seems easiest, and most future proof to use filenames rather than directory structure... The idea is that with regular expression pattern matching, all the info to generate the web pages comes from the file name. forecast_plot_search = '/group_workspaces/jasmin2/incompass/public/restricted/MetUM_Monitoring/project/' # Relative location of files, from forecast_plot_search sfiles = '*/*/*' # These three lines search for forecasts. 'T0' may need to be changed # depending on the file naming files = np.array(glob.glob(forecast_plot_search+sfiles)) f_inits = np.where(['T0' in f for f in files])[0] forecasts = np.unique([re.search(r'\d{8}_\d\dZ', os.path.basename(f)).group() for f in files[f_inits]]) # Where the template html files are script_path = '/home/users/pdwilletts/web_page_python_scripts/' TEMPLATE_FILE_f = "%sINCOMPASS_Jinja_Template_Forecast_regions.html" % script_path TEMPLATE_FILE_an = "%sINCOMPASS_Jinja_Template_Analysis.html" % script_path # Where html files will be, for viewing in browser web_page_dir = '/group_workspaces/jasmin2/incompass/public/restricted/MetUM/' relative_path = os.path.relpath(forecast_plot_search , web_page_dir)+'/' #pdb.set_trace() def GetParams(search_for, forecast_plot_search): ''' Splits globbed filenames by '_', and gets various info from them This may need to be edited for future use ''' paths = [os.path.relpath(fn, forecast_plot_search) for fn in glob.glob(search_for)] rel_paths = [fn.replace(re.search(r'_\d{8}_\d{2}Z_T\d+\S*', fn).group(), "") for fn in paths] regions_full = [fn.replace(re.search(r'\S*_T\d+', fn).group(), "").strip('.png') for fn in paths] regions = np.unique(regions_full) diags_full = np.array([os.path.basename(d) for d in rel_paths]) #pdb.set_trace() #diags = np.unique(diags_full) diags_full = np.array([''.join([d, r]) for d, r in zip(diags_full, regions_full)]) diags_reg = np.unique(diags_full) diags=[] for d in diags_reg: for r in regions[regions!='']: d = d.replace(r, "") diags.append(d) #pdb.set_trace() dates_times = np.array([re.search(r'_\d{8}_\d{2}Z_T\d+', fn).group() for fn in paths]) #pdb.set_trace() tpluss_full = np.array([re.search(r'T\d+', f).group().strip('T') for f in dates_times]) #pdb.set_trace() tpluss = np.sort(np.unique(np.array(tpluss_full)).astype(int)).astype(str) fdates = np.array([re.search(r'\d{8}', f).group() for f in dates_times]) fhours = np.array([re.search(r'\d\dZ', f).group() for f in dates_times]) return fdates, fhours, tpluss_full, tpluss, diags_full, diags, diags_reg, rel_paths, regions_full # Now for html page generation import jinja2 templateLoader = jinja2.FileSystemLoader( searchpath="/" ) templateEnv = jinja2.Environment( loader=templateLoader ) #Forecasts template = templateEnv.get_template( TEMPLATE_FILE_f ) #pdb.set_trace() for forecast in forecasts: #pdb.set_trace() fdates, fhours, tpluss_full, tpluss, diags_full, diags, diags_reg, rel_paths, regions_full \ = GetParams('%s*/%s/*' % (forecast_plot_search, forecast), forecast_plot_search) templateVars = { "fdates" : list(fdates), "fhours" : list(fhours), "tpluss_full" : list(tpluss_full), "rel_paths":list(rel_paths), "diags_full" : list(diags_full), "regions_full" : list(regions_full), "tpluss":list(tpluss), "diagnostics":list(diags_reg), "diags":list(diags), "image_dir":relative_path } outputText = template.render( templateVars ) with open("%sForecast_%s.html" %(web_page_dir, forecast), "wb") as fh: fh.write(outputText) # Analysis template = templateEnv.get_template( TEMPLATE_FILE_an ) fdates, fhours, tpluss_full, tpluss, diags_full, diags, diags_reg, rel_paths, regions_full \ = GetParams('%s*/*/*T0*' % (forecast_plot_search), forecast_plot_search) fdates_full = [('_').join([d,h]) for d,h in zip(fdates,fhours)] pdb.set_trace() templateVars = {"rel_paths":list(rel_paths), "diags_full" : list(diags_full), "regions_full" : list(regions_full), "fdates_un":list(np.unique(fdates_full)), "fdates_full":fdates_full, "diagnostics":list(diags_reg), "diags":list(diags), "image_dir":relative_path } outputText = template.render( templateVars ) with open("%s/Analysis.html" %(web_page_dir), "wb") as fh: fh.write(outputText)
4a1e6306f38ca900feaaa2e2eda81383f160bb54
[ "Python", "Shell" ]
2
Shell
peterwilletts24/INCOMPASS_Forecast_Website_JASMIN
ef4bc9bce0e66e963309b3a63167043cdb256b96
522efed0b43c5a41b32143c2e9652cc50621bf14
refs/heads/master
<repo_name>Twiknight/mvvm-toy<file_sep>/readme.md # mvvm-toy ------- This is a toy mvvm framework shipped with Twiknight's blog series: > Write a mvvm framework from scratch <file_sep>/example/build.js 'use strict' const webpack = require('webpack') const config = { entry: './main.js', output: { filename: 'bundle.js', path: '.' }, module: { loaders: [ { test: /\.js$/, exclunde: 'node_modules', loader: 'babel', query: { presets: ['es2015', 'stage-2'] } } ] } } webpack(config, function (err, stats) { if (err) { console.log(err) } let jsonStats = stats.toJson() if (jsonStats.errors.length > 0) { jsonStats.errors.forEach((x) => console.log(x)) } if (jsonStats.warnings.length > 0) { jsonStats.warnings.forEach((x) => console.log(x)) } })
7b4d3f3c73a265c56c918ae952792af47fd2b824
[ "Markdown", "JavaScript" ]
2
Markdown
Twiknight/mvvm-toy
ef2900f84e1bfe5b9e54c0d842b60427392b1a4d
bff7c4f81ff87f20ae0f696419e797e36efd2c73
refs/heads/master
<repo_name>goocksy/battleShip<file_sep>/battleship.js var checkDecks = function(element){ var currentI = element.getAttribute('i'); var currentJ = element.getAttribute('j'); var currentClass = element.getAttribute('class'); var decks = document.getElementsByClassName(currentClass); for (var i = 0; i < decks.length; i++){ console.log("i="+decks.item(i).getAttribute('i')+"|| j="+decks.item(i).getAttribute('j')+"class="+decks.item(i).className) } } /*Ответный огонь*/ var fireReturn = function(){ var i = parseInt(Math.random() * 10); var j = parseInt(Math.random() * 10); var z = document.getElementById(i+""+j); checkDecks(z); console.log('computer shooting') if (playerMap[i][j]=='s1' || playerMap[i][j]=='s2' || playerMap[i][j]=='s3' || playerMap[i][j]=='s4'){ z.className = 'dmg'; playerMap[i][j]='dmg'; enemyScore+=1; fireReturn(); }else if(playerMap[i][j]=='miss'){ fireReturn() }else if (playerMap[i][j]=='dmg') {fireReturn();} else{ z.className='miss'; playerMap[i][j]='miss'; } console.log("PCScore="+enemyScore); } function fire(element){ if (element.className=="s1e" || element.className=="s2e" || element.className=="s3e"||element.className=="s4e"){ element.setAttribute("class","dmg"); console.log("shot on the target!"); playerScore+=1; } else if (element.className=='dmg'){ alert('ti uje tuda bil') }else if(element.className=='miss'){ alert('ti uje tuda bil'); }else{ element.className='miss'; fireReturn(); } console.log("playerScore="+playerScore); } var setShip = function(i,j,typeShip,direction,mass,pl){ var p = pl; for (var l = 0; l < typeShip; l++){ if (direction==1){ p==1?mass[i+l][j]="s"+typeShip:mass[i+l][j]="s"+typeShip+"e"; if (j>0) mass[i+l][j-1]='z'; if (j<9) { mass[i+l][j+1]='z'; if (i>0) mass[i-1][j+1]='z'; } if (i>0){ mass[i-1][j]='z'; if (j>0) mass[i-1][j-1]='z'; } if (i<10-typeShip){ mass[i+typeShip][j]='z'; if (j>0) mass[i+typeShip][j-1]='z'; if (j<9) mass[i+typeShip][j+1]='z'; } }else{ p==1?mass[i][j+l]="s"+typeShip:mass[i][j+l]="s"+typeShip+"e"; if(i>0){ mass[i-1][j+l]='z'; } if (i<9){ mass[i+1][j+l]='z'; } if (j==0){ mass[i][j+typeShip]='z'; if (i<9) mass[i+1][j+typeShip]='z' if (i>0) mass[i-1][j+typeShip]='z' } if (j>0){ mass[i][j-1]='z'; if(i>0) mass[i-1][j-1]='z'; if(i<9) mass[i+1][j-1]='z'; if (j<9){ mass[i][j+typeShip]='z'; if (i>0) mass[i-1][j+typeShip]='z'; if (i<9) mass[i+1][j+typeShip]='z'; } } } } } var genShipsArrangement = function(mass,ts,playr){ var set = false; var p = playr; var typeShip = ts; while (!set){ var i = parseInt(Math.random() * 10); var j = parseInt(Math.random() * 10); var direction = parseInt(Math.random() * 2); var rj = j+typeShip; var ri = i+typeShip; if (direction == 1 & ri<11 & mass[i][j]=='w'){ if (ri>9){ continue; }else if(mass[ri][j]=='w') { set = true; setShip(i,j,typeShip,direction,mass,p) } } if (direction == 0 & rj<11 & mass[i][j]=='w'){ if (rj>9){ continue; }else if (mass[i][rj]=='w'){ set = true; setShip(i,j,typeShip,direction,mass,p) } } } } function init(){ var width = 10, height = 10; playerScore = 0; enemyScore = 0; player = document.querySelector('.js-player') enemy = document.querySelector('.js-enemy') playerMap = new Array(); enemyMap = new Array(); for (var i=0;i<width;i++){ playerMap[i] = new Array(); enemyMap[i] = new Array(); for (var j=0;j<height;j++){ playerMap[i][j] = 'w' enemyMap[i][j] = 'w' } } var score = 0; genShipsArrangement(playerMap,4,1) genShipsArrangement(playerMap,3,1) genShipsArrangement(playerMap,3,1) genShipsArrangement(playerMap,2,1) genShipsArrangement(playerMap,2,1) genShipsArrangement(playerMap,2,1) genShipsArrangement(playerMap,1,1) genShipsArrangement(playerMap,1,1) genShipsArrangement(playerMap,1,1) genShipsArrangement(playerMap,1,1) genShipsArrangement(enemyMap,4,2) genShipsArrangement(enemyMap,3,2) genShipsArrangement(enemyMap,3,2) genShipsArrangement(enemyMap,2,2) genShipsArrangement(enemyMap,2,2) genShipsArrangement(enemyMap,2,2) genShipsArrangement(enemyMap,1,2) genShipsArrangement(enemyMap,1,2) genShipsArrangement(enemyMap,1,2) genShipsArrangement(enemyMap,1,2) for (var i=0;i<width;i++){ for (var j=0;j<height;j++){ z=document.createElement('div') e=document.createElement('div') z.className = playerMap[i][j] e.className = enemyMap[i][j] z.id=i+""+j; z.setAttribute("i", i) z.setAttribute("j", j) e.setAttribute("i", i) e.setAttribute("j", j) e.setAttribute("onclick","fire(this)") player.appendChild(z) enemy.appendChild(e) } } }; window.addEventListener("DOMContentLoaded", init);
a9817623659080c6b4243f5eff146cc237c58f23
[ "JavaScript" ]
1
JavaScript
goocksy/battleShip
1b59cbe7f22cb1e28a076e07e82cc4c3b7de4e1c
1ba99f9c4bd1993a80ba8f4baad0b4238c35cbc5
refs/heads/master
<repo_name>HGLeoCho/a<file_sep>/sketch.js // Leo // Recursion function setup() { createCanvas(400, 400); } function draw() { background(50); stroke(255); noFill(); drawCircle(200, 200, 300); noLoop(); } function drawCircle(x, y, d) { ellipse(x, y, d); if (d > 2) { let newD = d * random(0.3, 0.9); drawCircle(x + newD, y, newD); drawCircle(x - newD, y, newD); //drawCircle(x, y + d * 0.5, d * 0.5); } } <file_sep>/README.md # Recursion [HTML Example](https://hgleocho.github.io/Recursion) <br/> <br/> <br/> Interactive Fractal Branches by <NAME> - [Demo](https://www.openprocessing.org/sketch/457282) | [Source](github.com/diegodelaefe/Fractaloid) * Alca - [Demo](https://codepen.io/Alca/full/pWaZaX/) | [Source](https://codepen.io/Alca/pen/pWaZaX/right) * Fractal Ball - jjwkdl - [Demo](https://jjwkdl.github.io/wordpress-content/javascript/fractal-ball/) | [Source](https://github.com/jjwkdl/wordpress-content/tree/master/javascript/fractal-ball) * <NAME> Recursive Remix - [Demo](https://recursion.glitch.me/) | [Source](https://glitch.com/edit/#!/recursion) * Recursive Squares - [Demo](https://codepen.io/DonKarlssonSan/full/PJQvKG) | [Source](https://codepen.io/DonKarlssonSan/pen/PJQvKG) * Recursive Koch Curve - [Demo](https://codepen.io/DonKarlssonSan/full/yzjywa) | [Source](https://codepen.io/DonKarlssonSan/pen/yzjywa) * Recursion Pyramid - Trevor Clarke: [Demo](https://trevorc.ca/recursionPyramid/) | [Source](https://github.com/Tr3v0rC/recursionPyramid)
091ba33642028c8567080268b0c58d1ccf815b61
[ "JavaScript", "Markdown" ]
2
JavaScript
HGLeoCho/a
1664f3c83fc2a2f1166fcd27040c9764f08f9ca1
ebda36044f12d1e35598c23151418dda01f49344
refs/heads/master
<repo_name>carlosgit2016/testxbrain<file_sep>/src/components/app/App.js // material-ui import { Container } from '@material-ui/core'; import { blue, orange } from '@material-ui/core/colors'; import { createMuiTheme } from '@material-ui/core/styles'; import { ThemeProvider } from '@material-ui/styles'; // react import React from 'react'; // fe-test-master import { products } from '../../data/products.json'; //imported products database import Products from '../Products'; import FinalizedPurchase from '../Finalized-Purchase'; //react-router-dom import { BrowserRouter as Router, Route } from "react-router-dom"; const theme = createMuiTheme({ palette: { primary: blue, secondary: orange }, }); const App = () => { return ( <div className="App"> <ThemeProvider theme={theme}> <Container> <Router> <Route exact path="/" component={() => (<Products products={products} ></Products>)} /> <Route path="/finish" component={FinalizedPurchase} /> </Router> </Container> </ThemeProvider> </div> ) } export default App; <file_sep>/src/components/Card/index.js //material-ui import { Button, Collapse, Fab, Grid, Input } from '@material-ui/core'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import { makeStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import AddIcon from '@material-ui/icons/Add'; import RemoveIcon from '@material-ui/icons/Remove'; //react import React from 'react'; //fe-test-master import './style.css'; import { addProductToCard } from '../../redux/actions/productsAction'; //react-redux import { connect } from 'react-redux'; //notistack import { useSnackbar } from 'notistack'; const useStyles = makeStyles({ card: { maxWidth: 345, width: "17em", minHeight: 387, minWidth: 272 }, price: { fontSize: "1.2rem" }, method: { fontSize: "0.7rem" }, fab: { fontSize: "0.6em" }, input: { alignItems: "center" }, grid: { marginTop: "1em" } }); const AddComponent = (props) => { function changeAmountValue(event, op) { event.stopPropagation(); event.preventDefault(); if (op === 'sum') plusCounter(); else if (op === 'subtraction') subtractionCounter(); } function plusCounter() { if (counter < 100) setCounter(counter + 1); } function subtractionCounter() { if (counter > 0) setCounter(counter - 1); } function clearCount() { setCounter(0); } const [counter, setCounter] = React.useState(0); function onAction() { props.onAction(counter); clearCount(); } return ( <Grid container spacing={3} > <Grid item xs={3}> <Fab aria-label="remove" size="small" onClick={(event) => changeAmountValue(event, 'subtraction')}> <RemoveIcon /> </Fab> </Grid> <Grid item xs={6}> <Input inputProps={{ style: { textAlign: 'center' } }} type='number' value={counter} fullWidth readOnly onChange={value => console.log(value)} /> </Grid> <Grid item xs={3}> <Fab aria-label="add" size="small" onClick={(event) => changeAmountValue(event, 'sum')}> <AddIcon /> </Fab> </Grid> <Grid item xs={12}> <Button variant="contained" color="primary" fullWidth onClick={onAction} disabled={counter === 0} > Adicionar </Button> </Grid> </Grid> ) } const CardComponent = (props) => { const classes = useStyles(); const { img, description, price, method } = props.product; const [showAdd, setAddProducts] = React.useState(false); const { enqueueSnackbar } = useSnackbar(); function handleExpandClick() { setAddProducts(showAdd => !showAdd); } function onSelectProduct(amount) { props.dispatch(addProductToCard(props.product,amount)); showMessage(`${amount} ${amount > 1 ? 'produtos' : 'produto' } adicionados com sucesso`, { variant: "success" }) } function showMessage(message, options) { enqueueSnackbar(message, options) } return ( <Card className={classes.card} onMouseLeave={handleExpandClick} onMouseEnter={handleExpandClick} > <CardContent> <CardMedia component="img" alt="Contemplative Reptile" height="auto" image={img} title="Contemplative Reptile" /> <Typography gutterBottom variant="subtitle2" component="h2"> {description} </Typography> <Typography className={classes.price}> R$ {price.toFixed(2)} </Typography> <Typography className={classes.method}> Em até {method.howManyTimes}x de {(price / method.howManyTimes).toFixed(2)} </Typography> <Typography className={classes.method}> R$ {method.inCash.toFixed(2)} à vista (10% de desconto) </Typography> <Collapse in={showAdd} > <AddComponent onAction={onSelectProduct} show={showAdd} ></AddComponent> </Collapse> </CardContent> </Card> ); } export default connect()(CardComponent);<file_sep>/src/redux/reducers/productsReducer.js import { ADD_PRODUCTS_TO_CARD, RESET } from '../actions/actionTypes' const initialState = { products: [], totalPrice: 0 } function addProduct(state, action) { let { products } = state; let { product: productToAdd, amount: amountToAdd } = action; let resultProduct = products.find(infoProduct => infoProduct.product.img === productToAdd.img); //using img how id state.totalPrice += action.product.price * action.amount; if (resultProduct) { resultProduct.amount += amountToAdd; return { ...state, products: [...products] }; } else { return { ...state, products: [...products, { product: action.product, amount: action.amount }] }; } } export default function productsReducer(state = initialState, action) { switch (action.type) { case ADD_PRODUCTS_TO_CARD: return addProduct(state, action); case RESET: return {products: [], totalPrice: 0}; default: return state; } }<file_sep>/src/components/Client-Data/index.js // material-ui import { Grid, MenuItem } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import TextField from '@material-ui/core/TextField'; // react import React from 'react'; //redux-form import { Field, reduxForm } from 'redux-form' const useStyles = makeStyles(theme => ({ textField: { marginLeft: theme.spacing(1), marginRight: theme.spacing(1), } })); const sexs = [ { value: "male", label: "Masculino" }, { value: "female", label: "Feminino" } ] const validate = values => { const errors = {} const requiredFields = [ 'name', 'sex', 'email' ] requiredFields.forEach(field => { if (!values[field]) { errors[field] = 'Required' } }) if (values.email && (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email))) { errors.email = "Endereço de email invalido" } return errors } const renderTextField = ({ input, label, meta: { touched, error }, ...custom }) => { return ( <TextField label={label} error={checkError(touched, error)} {...input} {...custom} /> ) } const renderSelectField = ({ input, label, children, meta: { touched, error }, ...custom }) => ( <TextField label={label} error={checkError(touched, error)} {...input} children={children} {...custom} > </TextField> ) function checkError(touched, error) { return touched && (typeof error === 'string'); } const ClientData = () => { const classes = useStyles(); return ( <form> <Grid container spacing={3}> <Grid item lg={5}> <Field id="name" name="name" component={renderTextField} label="Nome" InputLabelProps={{ shrink: true, }} fullWidth className={classes.textField} variant="outlined" margin="normal" placeholder="Nome do cliente aqui" /> </Grid> <Grid item lg={5}> <Field id="email" name="email" component={renderTextField} fullWidth label="Email" className={classes.textField} placeholder="Digite seu email aqui" margin="normal" variant="outlined" InputLabelProps={{ shrink: true, }}> </Field> </Grid> <Grid item lg={2}> <Field id="sex" name="sex" component={renderSelectField} fullWidth select label="Sexo" className={classes.textField} margin="normal" variant="outlined" InputLabelProps={{ shrink: true, }} > {sexs.map(sex => ( <MenuItem key={sex.value} value={sex.value}> {sex.label} </MenuItem> ))} </Field> </Grid> </Grid> </form> ) } export default reduxForm({ form: 'clientData', validate,destroyOnUnmount:false })(ClientData);<file_sep>/src/redux/reducers/index.js import { combineReducers } from 'redux'; import productsReducer from './productsReducer'; import { RESET } from '../actions/actionTypes'; import { reducer as reduxFormReducer } from 'redux-form'; function resetState(state = {}, action) { switch (action) { case RESET: return {}; default: return state; } } export default combineReducers({ productsReducer, form: reduxFormReducer, resetState });<file_sep>/src/components/Products/index.js // material-ui import { Box, Divider, Grid, Typography } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; // react import React from 'react'; // fe-test-master import Card from '../Card'; import CheckOut from '../CheckOut'; import ClientData from '../Client-Data/index'; const useStyles = makeStyles({ products: { maxWidth: "80em" }, title: { paddingTop: "3em", paddingBottom: "2em" } }); const Products = (props) => { const classes = useStyles(); return ( <div className={classes.products}> <div className={classes.title} > <Typography variant='h5'> Produtos </Typography> <Divider></Divider> </div> <Grid container spacing={3} justify="center" alignItems="center" > { props.products.map(product => { return <Grid key={product.img} item lg={3}><Card product={product} ></Card></Grid> }) } </Grid> <div className={classes.title} > <Typography variant='h5'> Dados do Cliente </Typography> <Divider></Divider> </div> <Box display="flex" flexDirection="row" flexWrap="wrap"> <Box width="100vw"> <ClientData></ClientData> </Box> <Box display="flex" flexDirection="column" width="100vw" alignSelf="flex-end"> <Box alignSelf="flex-end" pb={2} pt={2}> <CheckOut ></CheckOut> </Box> </Box> </Box> </div> ); } export default Products;<file_sep>/README.md # Teste desenvolvedor front-end ### A fazer - [x] Criar pagina de produto - [x] Criar pagina finalização de compra - [x] O usuário deve poder inserir a quantidade dos produtos desejados, inserir os dados nos formularios e finalizar a venda - [x] Na pagina de finalização da compra exibir o nome do cliente e o valor total da compra - [x] Colocar botão "Inicar nova compra" para redirecionar para tela de produtos ### Observações - Implementar as telas responsivas. :+1: - Inserir validações no formulário. :+1: - Pode-se personalizar qualquer component para se adequar ao design. :+1: - Não é necessário implementar nenhum código back-end, as informações ficarão todas armazenadas no browser. :+1: ### Tasks - Criar components necessários (Card, Client Data, Products, Finalized Purchase) :muscle: - Criar reducers e actions necessárias (client data, products) :muscle: - Criar input de produtos em formato JSON para ser consumido pela aplicação :muscle: - Construir component de card de acordo com o design :muscle: - Iterar sobre os produtos no component de produtos e construir todos os Cards necessários :muscle: - Ajustar Grid ao meio da tela :muscle: - Definir um estado para o preço total do produtos na Store :muscle: - Criar action para products para adicionar preço do produtos no estado de preço total :muscle: - Zerar contador após adicionar :muscle: - Mostrar mensagem no topo direito da tela que adicionou o produto e a quantidade :muscle: - Montar formulario usando redux form :collision: - Configurar router :muscle: - Apresentar informações no component Finalized Purchase :muscle:<file_sep>/src/redux/actions/actionTypes.js /** * Products Actions Types */ export const ADD_PRODUCTS_TO_CARD = "ADD_PRODUCTS_TO_CARD"; /** * Reset state to initialState */ export const RESET = "RESET";<file_sep>/src/utils/makeStylesMaterial.js const isBrowser = () => ![typeof window, typeof document].includes('undefined'); export default { isBrowser }<file_sep>/src/redux/actions/index.js import { addProductToCard } from './productsAction'; import { RESET } from './actionTypes'; const resetState = () => ({ type: RESET }); export { addProductToCard, resetState }<file_sep>/src/redux/actions/productsAction.js import { ADD_PRODUCTS_TO_CARD } from './actionTypes'; export const addProductToCard = (product,amount) => ({ type: ADD_PRODUCTS_TO_CARD, product, amount });
0344230202910fda420f90774b09968e018061fb
[ "JavaScript", "Markdown" ]
11
JavaScript
carlosgit2016/testxbrain
6a088217c667725266e313ddb4614e432d32625a
a1856adf94aec2d81ba2c88c3c9469c8237acce5
refs/heads/master
<repo_name>scor-pan/socket_server<file_sep>/socket_server.py # coding:utf-8 import socket EOL1 = b'\n\n' EOL2 = b'\n\r\n' body = '''Hello, world! <h1> form the5fire 《Django 企业开发实战》 </h1>''' response_params = [ 'HTTP/1.0 200 OK', 'Date: Sum, 27 may 2018 01:01:01 GMT', 'Content-Type: text/html; charset=utf-8', 'Content-Length: {}\r\n'.format(len(body.encode())), body, ] response = '\r\n'.join(response_params) def handle_connection(conn, addr): request = b'' while EOL1 not in request and EOL2 not in request: request += conn.recv(1024) ''' socket.recv(bufsize[,flags]) 从socket接收数据,返回值是一个代表所接收的数据的字节对象 一次性接收的最大数据量由bufsize指定,参数flags 通常忽略 ''' print(request) conn.send(response.encode()) # response 转为 bytes 后传输 ''' socket.send(data[,flags]) 将数据发送到socket python3中只能发送bytes类型的数据 ''' conn.close() ''' 关闭scoket 注:被调用后,连接断开,socket不能再发送数据,连接另一端也将不再接收数据。 ''' def main(): serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ''' socket.AF_INET 用于服务器与服务器之间的网络通信, socket.SOCK_STREAM 用于基于TCP的流式socket通信, socket.socket([family[, type[, proto]]]) 创建套接字, family: 套接字家族可以使AF_UNIX 或者AF_INET AF_UNIX ------------------- unix本机之间进行通信 AF_INET ------------------- 使用IPv4 AF_INET6 ------------------ 使用IPv6 type: 套接字类型可以根据是面向连接还是非连接分为 SOCK_STREAM(基于TCP)或者SOCK_DGRAM(基于UDP) SOCK_STREAM -------------- TCP套接字类型 SOCK_DGRAM ---------------- UDP套接字类型 SOCK_RAW ------------------ 原始套接字类型,这个套接字比较强大,创建这种套接字可以监听网卡上所有数据帧 SOCK_RDM ------------------ 一种可靠的UDP形式,即保证交付数据报但不保证顺序。 protocol: 一般不填默认为0 ''' serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ''' 在绑定前调用setsockopt 让套接字允许地址重用 设置端口可复用,保证我们每次按 Ctrl+C 组合键之后,快速重启 ''' serversocket.bind(('127.0.0.1', 8000)) ''' socket.bind(adress) 将socket绑定到地址(常用于服务端) address 地址的格式取决于地址族,在AF_INET下,以元组(host,port)的形式表示地址 ''' serversocket.listen(5) ''' # 设置backlog--socket 连接最大排队数量 socket.listen([backlog]) 启用服务器以接受连接(常用于服务端) backlog >= 0 ,指定系统在拒绝新连接之前将允许的未接受连接的数量。如果未指定,则选择默认的合理值 ''' print('http://127.0.0.1:8000') try: while True: conn, address = serversocket.accept() '''接受一个连接,但前提是socket必须依据绑定了一个地址,再等待连接。 返回值是一个(conn, address)的值对,这里的conn是一个socket对象,可以用来该送或接收数据。而address是连接另一端绑定的地址。 socket.getpeername( )函数也能返回该地址。''' handle_connection(conn, address) finally: serversocket.close() ''' 关闭scoket 注:被调用后,连接断开,socket不能再发送数据,连接另一端也将不再接收数据。 ''' if __name__ == '__main__': main()<file_sep>/simple_app.py~ # simple_app.py def simple_app(environ, start_response): ''' simple_app()函数就是一个符合WSGI标准的HTTP处理函数,它接受两个参数: environ :一个包含所有HTTP请求信息的 dict 对象 start_response :一个发送HTTP响应的函数 ''' status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) ''' 在simple_app()函数中,调用:start_response('200 OK',[('Content-Type','text/plain')] 就发送了HTTP响应的Header,注意Header只能发送一次,也就是只能调用一次start_response函数。 start_response()函数接受两个参数: 一个是HTTP响应码 一个是一组list 表示的HTTP Header,每个Header用一个包含两str 的tuple 表示。 ''' return [b'Hello world! -by the5ire \n'] '''然后,函数的返回值[b'Hello world! -by the5ire \n'] 讲作为HTTP响应的body 发送给浏览器''' '''这个simple_app()函数本身没有涉及到任何解析HTTP的部分,也就是底层代码不需要编写,我们只负责在更高层次上考虑如何响应请求就可以了'''
5789544d0c29bd12c587941b0358f72cd17adfa5
[ "Python" ]
2
Python
scor-pan/socket_server
8dd5019e6bc84128c329de8729adcb575ccf1b25
dde17779406fd498378717bf18a9f7cea1d6130c
refs/heads/master
<file_sep>import logging import base64 import json import os import pickle from email.mime.text import MIMEText from lxml import html import requests from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient import errors from googleapiclient.discovery import build STORE_URL = 'https://garynuman.tmstor.es/index.php?page=products&section=all&lf=454634a53a858c8c610454594289f92a' SCOPES = ['https://www.googleapis.com/auth/gmail.send'] # Enable logging logging.basicConfig( filename='log.txt', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) def send_mail(config, removed, added): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) message = '' if removed: message += "Productos eliminados:\n" for p in removed: message += f'- {p}\n' message += '\n' if added: message += 'Productos añadidos:\n' for p in added: message += f'- {p}\n' message += '\n' message += STORE_URL message = MIMEText(message) message['to'] = config['to_addr'] message['from'] = config['from_addr'] message['subject'] = 'Cambios en la tienda de <NAME>!!!' message = {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()} try: message = (service.users().messages().send(userId='me', body=message) .execute()) logger.info('Message Id: %s' % message['id']) except errors.HttpError as error: logger.error('An error occurred: %s' % error) def check_site(config): if os.path.exists('last.pickle'): with open('last.pickle', 'rb') as file: last = pickle.load(file) else: last = [] response = requests.get(STORE_URL) tree = html.fromstring(response.content) products = tree.xpath('//span[@class="productTitle"]/text()') if last and products != last: send_mail(config, set(last) - set(products), set(products) - set(last)) logger.info('Check made') with open('last.pickle', 'wb') as file: pickle.dump(products, file) def main(): with open('config.json') as file: check_site(json.load(file)) if __name__ == '__main__': main() <file_sep>cd "$HOME/gnuman/" || exit venv/bin/python gnuman.py
1505e4ce00ddd235ae7ad6d50199ed0ddc7fa721
[ "Python", "Shell" ]
2
Python
ealmuina/gnuman
1847c0016bac9c5096080fb823474245a6d5fef4
ce10ab3287b57c963cfffc8877614cd99ad3dc96
refs/heads/master
<repo_name>bantenprov/project<file_sep>/src/routes/web.php <?php Route::group(['prefix' => 'project','middleware' => 'web'], function() { Route::get('demo', 'Bantenprov\Project\Http\Controllers\ProjectController@demo'); Route::get('/','Bantenprov\Project\Http\Controllers\ProjectController@index')->name('projectIndex'); Route::get('/view/{id}','Bantenprov\Project\Http\Controllers\ProjectController@show')->name('projectShow'); Route::get('/edit/{id}','Bantenprov\Project\Http\Controllers\ProjectController@edit')->name('projectEdit'); Route::get('/delete/{id}','Bantenprov\Project\Http\Controllers\ProjectController@destroy')->name('projectDelete'); Route::get('create', 'Bantenprov\Project\Http\Controllers\ProjectController@create')->name('projectCreate'); Route::post('store', 'Bantenprov\Project\Http\Controllers\ProjectController@store')->name('projectStore'); }); <file_sep>/src/Exceptions/ProjectException.php <?php namespace Bantenprov\Project\Exceptions; use Exception; /** * The ProjectException class. * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ class ProjectException extends Exception { // } <file_sep>/src/Contracts/ProjectInterface.php <?php namespace Bantenprov\Project\Contracts; /** * The ProjectInterface interface * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ interface ProjectInterface { // } <file_sep>/src/Http/Controllers/ProjectController.php <?php namespace Bantenprov\Project\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Bantenprov\Project\Facades\Project; use Bantenprov\Project\Models\Project as ProjectModel; use Bantenprov\Staf\Models\Staf; use Validator; /** * The ProjectController class. * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ class ProjectController extends Controller { protected $projectModel; protected $stafModel; public function __construct() { $this->projectModel = new ProjectModel(); $this->stafModel = new Staf(); } public function index() { $projects = $this->projectModel->paginate(10); return $projects; //return view('project::project.index',compact('projects')); } public function create() { $stafs = $this->stafModel->all(); return $stafs; //return view('project::project.create',compact('stafs')); } public function store($req) { $validator = Validator::make($req, [ 'staf_id' => 'required', 'name' => 'required', 'start_date' => 'required|date', 'end_date' => 'required|date', 'description' => 'required', ]); if ($validator->fails()) { return redirect()->back() ->withErrors($validator) ->withInput(); } $store = $req; array_set($store,'opd_id',$this->stafModel->find($req['staf_id'])->opd_id); $this->projectModel->create($store); return redirect()->back()->with('message','Success add data'); } public function show($id) { $project = $this->projectModel->find($id); return $project; } public function edit($id) { $stafs = $this->stafModel->all(); $project = $this->projectModel->find($id); $response = (object) ['project' => $project,'stafs' => $stafs]; return $response; } public function update($id, $req) { $validator = Validator::make($req, [ 'staf_id' => 'required', 'name' => 'required', 'start_date' => 'required|date', 'end_date' => 'required|date', 'description' => 'required', ]); if ($validator->fails()) { return redirect()->back() ->withErrors($validator) ->withInput(); } $store = $req; array_set($store,'opd_id',$this->stafModel->find($req['staf_id'])->opd_id); $this->projectModel->find($id)->update($store); return redirect()->back()->with('message','Success update data'); } public function destroy($id) { $this->projectModel->find($id)->delete(); return redirect()->back(); } public function countProject() { $result = $this->projectModel->all()->count(); return $result; } public function demo() { return Project::welcome(); } } <file_sep>/src/helpers/helpers.php <?php if (! function_exists('project')) { function project() { return 'Welcome to function project() for Bantenprov\Project package'; } } <file_sep>/src/Contracts/ProjectAbstract.php <?php namespace Bantenprov\Project\Contracts; /** * The ProjectAbstract class * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ abstract class ProjectAbstract { // } <file_sep>/README.md # Project Project package used in Task Management application <file_sep>/src/config/config.php <?php return [ /* |-------------------------------------------------------------------------- | Demo Config |-------------------------------------------------------------------------- | | The following config lines are used for development of package | Bantenprov/Project | */ 'key' => 'value', 'models' => [ 'staf' => 'Bantenprov\Staf\Models\Staf' ] ]; <file_sep>/src/Project.php <?php namespace Bantenprov\Project; use Bantenprov\Project\Http\Controllers\ProjectController; /** * The Project class. * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ class Project { protected $projectController; public function __construct() { $this->projectController = new ProjectController; } public function welcome() { return 'Welcome to Bantenprov\Project package'; } public function projectIndex() { return $this->projectController->index(); } } <file_sep>/src/Models/Project.php <?php namespace Bantenprov\Project\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * The ProjectModel class. * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ class Project extends Model { use SoftDeletes; protected $table = 'project'; public $timestamps = true; protected $fillable = ['opd_id','staf_id','name','start_date','end_date','description']; protected $hidden = ['deleted_at']; protected $dates = ['deleted_at']; /* relation table */ // public function task() // { // return $this->belongsTo('App\Task'); // } public function getOpd() { return $this->hasOne('App\Opd', 'id','opd_id'); } public function getStaf() { return $this->hasOne(config('project.models.staf'),'id','staf_id'); } } <file_sep>/src/Facades/Project.php <?php namespace Bantenprov\Project\Facades; use Illuminate\Support\Facades\Facade; /** * The Project facade. * * @package Bantenprov\Project * @author bantenprov <<EMAIL>> */ class Project extends Facade { /** * Get the registered name of the component. * * @return string */ protected static function getFacadeAccessor() { return 'project'; } }
f5eec8fd96fb78584a68d38fc1abb75c519968c7
[ "Markdown", "PHP" ]
11
PHP
bantenprov/project
49e461d44434ceec0f8228776d91068e4fbb96a4
ca21f0eb0c8df86ef50e0ff41705fc1e754c2b97
refs/heads/master
<repo_name>youyuebingchen/chatbot<file_sep>/nlp_basic_knowledge/chatbot02.md # chatbot 第二课 (july online) --- ## NLP 基础 nltk为基础 --- ### nltk http://www.nltk.org 推荐3.4(很多都是以3.4为基石)<br/> python 上注明的自然语言处理库<br/> - 自带语料库,词性分类库。安装完成后下载语料库 nltk.download() - 自带分类,分词,(并行能力)等功能<br/> nltk.corpus,tokenize(分析),paring(句子shu),stem - 强大的社区支持 - 还有n多的简单版wrapper --- ### 文本处理流程 raw_text --->tokenize (-->POStag) --->lemma/stemming --->stopwords --->wordlist #### 分词 - 启发式heuristic(查字典) - 机器学习、统计方法(基于数据):HMM、CRF(具体公式)、nn、lstm(训练) - 英文:tokenize - 中文:jieba 启发式:cut(cur_all=True/Fasle) viterbi算法,cut_for_search()模式更精确 - 分词之后被分成一个个单词list ##### 难点 - 社交网络语言的tokenize: 正则表达式 - 纷繁复杂的词形:1、inflection(时态)变化 2、derivation(词性)变化 #### 词形归一化 - stemming 词干提取,就是把不影响词性的inflection的小尾巴去掉<br/> nltk.stem.porter lancaster snowballstemmer - lemmatization 词形归一:把各种类型的词的变形都归为一种形式<br/> nltk.stem wordnetlemmatizer 通过查表的方式还原成原形<br/> 问题:比如 went ->go ->温斯特 解决:加上pos tag 默认是名词nn<br/> part of speech(POS) table:nltk.pos_tag((text)) 先pos 再lemma #### 停用词 - nltk.cropus stopwords<br/> [word for word in wordlist if word not in stopwords.words("english")]<br/> 去除停用词后得到一个干净的数据列表,后续应用数据进行模型训练 ### makefeatures --- ### NLP经典三个案例 #### 情感分析 ##### 情感词库 类似于关键词打分机制,稳定但不够高级 - 建一个字典,word :scroe,查看要打分句子分词后的词在字典中的分值进行加和 - 问题:太 naive 1、新词怎么办2、特殊词汇怎么办 3、更深层次的玩意怎么办 ##### 配上ML的情感分析 先分词再打标签然后进行机器学习训练然后分类 #### 文本相似度 先向量化 ##### 余弦定理 #### 文本分类 - TF term frequency 衡量一个term在文档中出现的频繁程度。<br/> TF(t) = (t在文档中的次数)/(文档中所有term的总数) - IDF inverse document frequency 衡量一个term的重要性。<br/> 降低常用词的重要性,提升罕见次的重要性。<br/> IDF(t) = log(文档总数/含有t的文档的总数) - TF-IDF = TF*IDF - 实现 使用nltk.text 中TextCollection:这个类会自动帮忙断句做统计做计算<br/> cropus = textcollection([.....]) --- corpus.tf_idf("word","sentence") --- ### 深度学习加持 deep learn is a branch of machine learning based on a set of algorithms that attempt to model high level abstractions in data of multiple linear and non-lineaar transformations #### autoencoder 自编码器:将信息编码处理,再解码 data-specific ### word2vec(mikolov,2013) ##### lexical taxonomy 词汇分类:wordNet(miller,1900) - static 每隔一段时间就要更新 - 只有英语有 ##### symbolic representation 符号表示: One-hot(turian et al. 2010) - 可以表达所有的单词向量 - 单词间的关系不能计算出来 ##### distributional similarity based representation 相似度表示 ##### fulldocumen:TF-IDF ##### window: co-occurrence matrix + SVD (Bullinaria& levy,2012) - 共线矩阵,精准到语境本身 #### CBOW - input为周围词语,输出为当前词 #### skip gram - 只给中间词猜周围词都是哪些。会让生僻词曝光率更高, - 对于小规模的训练数据集很好 <file_sep>/rule_basedchatbot/upgrate_1_rule_based.py from nltk import word_tokenize import random greeting = ["hola","hello","hi","Hi","hey","hey!"] question = ["break","holiday","vacation","weekend"] responses = ["It was nice! I went to paris","Sadly, I just stayed at home"] while True: rand_greeting = random.choice(greeting) rand_respon = random.choice(responses) usrinput = input(">>>") cleand_input = word_tokenize(usrinput) if not set(cleand_input).isdisjoint(greeting): print(rand_greeting) elif not set(cleand_input).isdisjoint(question): print(rand_respon) elif usrinput == "bye": break else: print("I don't know what you are saying")<file_sep>/nlp_basic_knowledge/chatbot.md # ChatBot 第一课(july online) ## 行业综述 ### bot的定义 ------ bot:执行大量的自动化告诉挥着机械师繁琐的编辑工作的计算机程序或者脚本以及其所登陆的账户 ### chatbot的玩法 ------- - retrieved-based(基于提取): KE(knowledge enger)专家系统(知识库检索)。<br/> 问题:计算速度是要解决的问题<br/> 提升:intents 机制(归类) 也就是在框架的前边加一个文本分类器 - generative 例RNN,生成一些人没有想到的。(必读《a neural conversational model》开启了generative model的新纪元)<br/> chatterBot库 - 知识框架<br/> | |chatbot conversation framework | |------------ |-------------------:|:-------: | | open Domain | impossible |geneal AI(hardest) | |closed domain| rules-based(easiest| smart machine(hard)| | |retrieval-based(人设)|generative-based(数据驱动)| ### chatbot目前的challenge - 语境 <br/> paper1:build end to end dialoge systems using generative hierarchical neural network model<br/> paper2:attion whit intention for a neural network conversation model <br/> 语言的语境<br/> 物理的语境 - 统一的语言个性(容易精神分裂)<br/> 高质量的对话:清洗,花费时间太久<br/> paper: a persona-based neural conversation model<br/> 通过心里学和文本推算出是哪种性格的人 - 模型验证<br/> BLEU验证 *我们自己对模型的正误哦按段需要人类的智慧的解读<br/> *不存在完美定义的方案<br/> paper: how bot to evaluate dialogue system:an empirical study of unsupervised evaluation metrics for dialogue response generation - 多样性 回答不够多样性比如无论问什么都回答嗯<br/> 出现原因:数据集<br/> paper:a diversity-promoting objective function for neural conversation modeals ----- ### 工业应用综述 - 语音助手( 主动/被动) - 餐饮 - 旅游 - 医疗:前台healthtop 很多都是做前台 - 新闻 - 财经 - 健身 ----- ### 工业上的一些坑 - 查找 -> 发现 - 基于知识库 -> 基于检索 - 基于规则 -> 基于数据 - app -> 智能硬件 智能家居 ----- ### rule-based 机器人 - grade0:基本的问答事前准备好所有可能的问答情况,然后根据问题做出固定的反应 不能理解理解问题人在问什么 ----- ### 升级! - grade1.0:精准对答。通过关键词来判断这句话的意图。<br/> 先用 word_tokenize分词,然后查看共有词。set(a).isdisjoint(b):查看a和b 集合是否具有共同的元素,如果没有返回True,如果有返回Fasle - upgrade2.0:先建立知识体系库(构建知识图谱),建一套体系,然后通过搜索的方法来查询答案。<br/> 也可以使用logic programming prolog python的prolog:PyKE - upgrade3.0:利用gTTs把文本转化成音频。相当于为了提升用户体验多加了一个前端。<br/> 其他场景:微信、slack、Facebook messager等<br/> 目前工业上根本不可能实现智能对话,还有很长的路要走。 <file_sep>/nlp_basic_knowledge/sentiment_classify_dictionary/sentiment_with_ml.py from nltk.classify import NaiveBayesClassifier # 分词打标签然后进行训练 def preprocess(s): return {word:True for word in s.lower().split()} s1 = " " s2 = " " s3 = " " s4 = " " training_data = [[preprocess(s1),"pos"], [preprocess(s2),"pos"], [preprocess(s3),"neg"], [preprocess(s4),"neg"]] model = NaiveBayesClassifier.train(training_data) print(model.classify(preprocess("this is a good book"))) <file_sep>/rule_basedchatbot/basical_rule_based_chatbot.py import random greeting = ["hola","hello","hi","Hi","hey","hey!"] # random_greeting = random.choice(greeting) question = ["how are you","how do you do"] response = ["ok, i am fine","fine thanks, and you ?","very well"] # random_response = random.choice(response) while True: userinput = input(">>>") if userinput in greeting: print(random.choice(greeting)) elif userinput in question: print(random.choice(response)) elif userinput == "bye": break else: print("I don't know what do you say!") <file_sep>/rule_basedchatbot/upgrade_2_rule_based.py # 先建立一个基于目标行业的database graph = {"上海":["苏州","常州"], "苏州":["常州","镇江"], "常州":["镇江"], "镇江":["常州"], "盐城":["南通"], "南通":["常州"]} # 明确如何从A 到 B def findpath(start,end,path=[]): path = path + [start] if start == end: return path if start not in graph: return "没有路径" for node in graph[start]: if node not in path: newpath = findpath(node,end,path) if newpath: return newpath return "没有路径" print(findpath("上海","广州"))<file_sep>/nlp_basic_knowledge/sentiment_classify_dictionary/sentiment_dic.py import nltk str = " i love it very much" words = nltk.cut(str) sentiment_dic = {} for line in open("AFINN-111.text"): word,score = line.split("\t") sentiment_dic[word]=int(score) total_score= sum(sentiment_dic.get(word,0) for word in words) <file_sep>/nlp_basic_knowledge/lib_nltk_use.py # #从语料库中引入brown大学的语料库 # from nltk.corpus import brown # # a = brown.categories() # print(a) # print(len(brown.sents())) # print(len(brown.words())) # # 词频统计 # import nltk # from nltk import FreqDist # corpus = "this is my sentence this is my life this is the day" # tokens = nltk.word_tokenize(corpus) # print(tokens) # fdist = FreqDist(tokens) # # print(fdist.items()) # # 选取最常用的单词构建向量空间 # standard_freq_vector = fdist.most_common(50) # size = len(standard_freq_vector) # print(standard_freq_vector) # stand_word_dic = [list(w)[0] for w in standard_freq_vector] # # # 对新句子进行编码 # sentence = ["this","is","my","favoriate","pen"] # size = len(sentence) # # 县初始化一个向量 # sent_vec = [0]*size # i = 0 # for word in sentence: # try: # if word in stand_word_dic: # sent_vec[i] = 1 # i+=1 # except KeyError: # # 不在词汇表中的直接略过 # i+=1 # continue # print(sent_vec) # nltk实现TF-IDF from nltk.text import TextCollection corpus = TextCollection(["this is sentence one","this is sentence two","this is sentence three"]) print(corpus) print(corpus.tf_idf("this","this is sentence four"))
3e106794dfc38b5cccf378a4631a6d0d34a92022
[ "Markdown", "Python" ]
8
Markdown
youyuebingchen/chatbot
52c4dbca26eb3186e663bb8ae75e1b8370de7e98
f0e3de3f7e8404b36a3a6f6df26e516c1b02f3e5
refs/heads/master
<repo_name>SiamakEshghi/would-you-rather<file_sep>/src/modules/login/actions.js import * as data from '../../utils/Data' import * as t from './actionTypes'; export const loginUser= (value, callBack) => { return dispatch => { dispatch({ type: t.LOG_IN, logged: value !== '' }); } } export const logOut = () => { return { type: t.LOG_OUT } }<file_sep>/src/modules/Question/screen/Question.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { Button, Image } from 'react-bootstrap'; import { selectAnswer } from '../../../Public/actions'; class Question extends Component { state = { isAnswered: false, } componentDidMount = () => { const { currentQuestion, currentUser } = this.props; this.isAnswered(currentUser.answers, currentQuestion.id); } optionTapped = (e, selectedOption) => { e.preventDefault(); const { currentQuestion, currentUser, selectAnswer } = this.props; selectAnswer(currentUser.id, currentQuestion.id, selectedOption, () => this.setState({ isAnswered: true })); } isAnswered = (answers, questionId) => { if (answers.hasOwnProperty(questionId)) { this.setState({ isAnswered: true }); }else{ this.setState({ isAnswered: false }); } } getPercent = (question, option) => { const numberOfVotesfOptionOne = question.optionOne.votes.length; const numberOfVotesfOptionTwo= question.optionTwo.votes.length; if (option === 1) { return (numberOfVotesfOptionOne / (numberOfVotesfOptionOne + numberOfVotesfOptionTwo)) * 100; } else if (option === 2) { return (numberOfVotesfOptionTwo / (numberOfVotesfOptionOne + numberOfVotesfOptionTwo)) * 100; } } renderAnsweredOptions = () => { const { currentQuestion, currentUser, questionAuthor } = this.props; return ( <div> <div > <h2>{questionAuthor.name}</h2> <Image style={styles.image} src={questionAuthor.avatarURL} /> <h1>...............................................................</h1> </div> <div> <div> <h2>{currentQuestion.optionOne.text}</h2> <h3>{currentQuestion.optionOne.votes.length}</h3> <h4>{this.getPercent(currentQuestion, 1)} %</h4> </div> <h1>...............................................................</h1> <div> <h2>{currentQuestion.optionTwo.text}</h2> <h3>{currentQuestion.optionTwo.votes.length}</h3> <h4>{this.getPercent(currentQuestion, 2)} %</h4> </div> </div> </div> ); } renderNotAnsweredOptions = () => { const { currentQuestion, currentUser, questionAuthor } = this.props; return ( <div> <div > <h1>Would You Rather</h1> <h4>Select an option!</h4> <h2>{questionAuthor.name}</h2> <Image style={styles.image} src={questionAuthor.avatarURL} /> <h1>...............................................................</h1> </div> <div> <div> <h2>{currentQuestion.optionOne.text}</h2> <Button onClick={(e) => this.optionTapped(e, "optionOne")} >Click</Button> </div> <h1>...............................................................</h1> <div> <h2>{currentQuestion.optionTwo.text}</h2> <Button onClick={(e) => this.optionTapped(e, "optionTwo")} >Click</Button> </div> </div> </div> ); } render() { const { currentQuestion, currentUser } = this.props; const { isAnswered } = this.state; if(currentUser && currentQuestion != null){ if (isAnswered) { return (this.renderAnsweredOptions()); } else { return (this.renderNotAnsweredOptions()); } } else { return <div>There is no question.</div> } } } const styles = { text: { textAlign: 'center' }, image: { height: 50, width: 50 } } const mapStateToProps = ({ pub }, props) => { const { id } = props.match.params; const { questions, currentUser, users } = pub; const currentQuestion = questions[id] || null; const questionAuthorId = currentQuestion ? currentQuestion.author : null const questionAuthor = users[questionAuthorId] || null return { currentQuestion, currentUser, questionAuthor }; } export default withRouter(connect(mapStateToProps, {selectAnswer})(Question));<file_sep>/src/modules/dashboard/component/Card/Card.js import React from 'react'; import {getDate} from '../../../../utils/dateHelper'; import { Link } from 'react-router-dom'; const Card = ({question, isDone}) => { const { author, timestamp, id } = question; if (question === null) { return <p>This question doesn't exist</p>; } return( <Link to={`/questions/${id}`}> <h2>{author}</h2> <h3>{getDate(timestamp)}</h3> </Link> ); }; export default Card;<file_sep>/src/modules/dashboard/screen/Dashboard.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { ListGroup, ListGroupItem } from 'react-bootstrap'; import Card from '../component/Card/Card'; class Dashboard extends Component { render() { const { unansweredId, answeredId, questions} = this.props; return( <div> <h1>------------------------ New Questions --------------------------</h1> <div> <ListGroup> {unansweredId.map(id => { const unansweredQuestion = questions[id]; return( <ListGroupItem key={id} onClick={()=> console.log(id)}> <Card question={unansweredQuestion} /> </ListGroupItem> ); }) } </ListGroup> </div> <h1>------------------------ Done --------------------------</h1> <div> <ListGroup> {answeredId.map(id => { const answeredQuestion = questions[id]; return( <ListGroupItem key={id} onClick={()=> console.log(id)}> <Card question={answeredQuestion} /> </ListGroupItem> ); }) } </ListGroup> </div> </div> ) } } const mapStateToProps = ({ pub }) => { const { questions, currentUser } = pub const answeredId = (currentUser && questions) ? Object.keys(currentUser.answers).sort( (a, b) => questions[b].timestamp - questions[a].timestamp ) : []; const unansweredId = questions ? Object.keys(questions) .filter(question => { return answeredId.indexOf(question) === -1; }) .sort((a, b) => questions[b].timestamp - questions[a].timestamp) : []; return {answeredId, unansweredId, questions} } export default connect(mapStateToProps)(Dashboard);<file_sep>/src/modules/board/screen/Board.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Image } from 'react-bootstrap'; class Board extends Component { render() { const { users, userIdList } = this.props; if(users.length === 0 || userIdList === 0) { return( <div></div> ); } return( <table style={{width: '100%'}}> <thead> <tr> <th>User</th> <th>Answered</th> <th>Created</th> </tr> </thead> <tbody> {userIdList.map((id) => { const user = users[id]; return ( <tr key={id}> <td style={styles.text}> <Image style={styles.image} src={user.avatarURL} /> <h2>{user.name}</h2> <h3>{user.id}</h3> </td> <td style={styles.text}>{Object.keys(user.answers).length}</td> <td style={styles.text}>{user.questions.length}</td> </tr> )} )} </tbody> </table> ); } } const styles = { text: { textAlign: 'center' }, image: { height: 50, width: 50 } } const mapStateToProps = ({ pub }) => { const { users } = pub; const userIdList = Object.keys(users).sort( (a, b) => Object.keys(users[b].answers).length + users[b].questions.length - (Object.keys(users[a].answers).length + users[a].questions.length) ); return {users, userIdList} } export default connect(mapStateToProps)(Board);<file_sep>/src/Public/reducer.js import * as t from './actionTypes'; const INITIAL_STATE = { currentUser: null, users: [], questions: [] } const publicReducer = (state={INITIAL_STATE}, action) => { switch (action.type) { case t.SET_CURRENT_USER: return {...state, currentUser: action.currentUser} case t.SET_USERS: return {...state, users: action.users } case t.SET_QUESTIONS: return {...state, questions: action.questions} case t.SAVE_CURRENT_ANSWER: const {answer, qid, authedUser} = action.answer // console.log(`currentUser: ${JSON.stringify(state.currentUser)}`) // console.log(`CurrentQuestions: ${JSON.stringify(state.questions[qid])}`) console.log(`Users: ${JSON.stringify(state.users[authedUser])}`) return { ...state, currentUser: {...state.currentUser, answers: {...state.currentUser.answers, [qid]: answer }, }, questions: {...state.questions, [qid]: {...state.questions[qid], [answer]: { ...state.questions[qid][answer], votes: state.questions[qid][answer].votes.concat([authedUser]) } } }, users: {...state.users, [authedUser]: {...state.users[authedUser], answers: { ...state.users[authedUser].answers, [qid]: answer } } } } case t.SAVE_NEW_QUESTION: const { question } = action; return { ...state, currentUser: { ...state.currentUser, questions:{ ...state.currentUser.questions, question } }, questions: { ...state.questions, [question.id]: question } } default: return INITIAL_STATE; } } export default publicReducer;<file_sep>/src/modules/login/reducer.js import * as t from './actionTypes'; const INITIAL_STATE = { logged: false } const loginReducer = (state={INITIAL_STATE}, action) => { switch (action.type) { case t.LOG_IN: return {...state, logged: action.logged } case t.LOG_OUT: return INITIAL_STATE; default: return state; } } export default loginReducer;<file_sep>/src/modules/newQuestion/screen/NewQuestion.js import React, { Component } from 'react'; import {connect} from 'react-redux'; import { saveNewQuestion } from '../../../Public/actions'; class NewQuestion extends Component { state = { firstOption: '', secondOption: '', isDone: false } handleChange = (e, order) => { const text = e.target.value switch (order) { case 'first': this.setState(() => ({ firstOption: text })); break case 'second': this.setState(() => ({ secondOption: text })); break default: return } } handleSubmit = (e) => { e.preventDefault() const { currentUser, saveNewQuestion } = this.props; const { firstOption, secondOption } = this.state; saveNewQuestion(currentUser.id, firstOption, secondOption, () => this.setState({ isDone: true })); } render(){ if (this.state.isDone) { return ( <div> <h2>New Question is saved!</h2> <button onClick={() => this.setState({ isDone: false })}> Done! </button> </div> ); } return( <div> <h1>Creat new question</h1> <form className='new-tweet' onSubmit={this.handleSubmit}> <textarea placeholder="First Option" onChange={ (e) => this.handleChange(e, 'first')} /> <textarea placeholder="Second Option" onChange={(e) => this.handleChange(e, 'second')} /> <div> <button type='submit'> Submit </button> </div> </form> </div> ); } } const mapStateToProps = ({ pub }) => { const { currentUser, questions } = pub; return { currentUser, questions }; } export default connect(mapStateToProps, { saveNewQuestion })(NewQuestion);<file_sep>/src/modules/login/screen/Login.js import React, { Component } from 'react' import { connect } from 'react-redux'; import { loginUser } from '../actions'; import { handleInitialData } from '../../../Public/actions'; // const BUTTONS = ['Default']; class Login extends Component { changeValue = (val) => { const { loginUser, handleInitialData, history } = this.props; const value = val.target.value; loginUser(value); handleInitialData(value); history.push('/dashboard') } render() { return( <div> <h1>Login</h1> <h1>---------------------------</h1> <h2>Select user</h2> <select onChange={this.changeValue}> <option value=''>Select</option> <option value="sarahedo"><NAME></option> <option value="tylermcginnis"><NAME></option> <option value="johndoe"><NAME></option> </select> </div> ); } } export default connect(null, { loginUser, handleInitialData })(Login);<file_sep>/src/redux/reducer.js import { combineReducers } from 'redux'; import loginReducer from '../modules/login/reducer'; import publicReducer from '../Public/reducer'; export default combineReducers ({ log: loginReducer, pub: publicReducer, })<file_sep>/src/modules/App/screen/App.js import React, { Component, Fragment } from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom' import { connect } from 'react-redux'; // import LoadingBar from 'react-redux-loading' import Dashboard from '../../dashboard/screen/Dashboard'; import NewQuestion from '../../newQuestion/screen/NewQuestion'; import Board from '../../board/screen/Board' import Question from '../../Question/screen/Question' import Nav from './component/Nav'; import Login from '../../login/screen/Login'; import { logOut } from '../../login/actions'; class App extends Component { logOut = () => { this.props.logOut(); } render() { const { isLogged } = this.props; const NotValid = ({ location }) => ( <div> <h2> Error 404 </h2> <h3> No match for <code>{location.pathname}</code> </h3> <Link to='/'>Please Login First</Link> </div> ); if (!isLogged) { return ( <Router> <Switch> <Route exact path='/' exact component={Login} /> <Route component={NotValid} /> </Switch> </Router> ); } return ( <Router> <Fragment> <div > <Nav logOut={this.logOut}/> <div> <Switch> <Route path='/dashboard' component={Dashboard} /> <Route path='/add' component={NewQuestion} /> <Route path='/board' component={Board} /> <Route path='/questions/:id' component={Question} /> <Route component={NotValid} /> </Switch> </div> </div> </Fragment> </Router> ); } } function mapStateToProps({ log }) { const isLogged = log.logged ? log.logged : false return { isLogged }; } export default connect(mapStateToProps, { logOut })(App);
579c281e88140199fa5b8be5c22f05dd14048030
[ "JavaScript" ]
11
JavaScript
SiamakEshghi/would-you-rather
c5b1f11067ac1e37bd3730ee0f76ed370a5bc338
1a2fc6cbd024fd72e0e4d4f5b3159482c37ed091
refs/heads/main
<repo_name>varunpadaki/mytunes-angular-ui<file_sep>/src/app/store-management/store-management.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StoreManagementRoutingModule } from './store-management-routing.module'; import { CreateStoreComponent } from './create-store/create-store.component'; import { ViewStoreComponent } from './view-store/view-store.component'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { MaterialModule } from '../material/material.module'; import { StoreManagerComponent } from './store-manager/store-manager.component'; @NgModule({ declarations: [CreateStoreComponent, ViewStoreComponent, StoreManagerComponent], imports: [ CommonModule, StoreManagementRoutingModule, MaterialModule, ReactiveFormsModule, FormsModule ] }) export class StoreManagementModule { } <file_sep>/src/app/alerts/alert/alert.component.ts import { Component, OnInit, Input } from '@angular/core'; import { Alert, AlertType } from '../model/Alert'; import { Subscription } from 'rxjs'; import { AlertService } from '../service/alert.service'; @Component({ selector: 'app-alert', templateUrl: './alert.component.html', styleUrls: ['./alert.component.scss'] }) export class AlertComponent implements OnInit { @Input() id = "default-alert"; @Input() fade = true; alerts: Alert[] = []; alertSubscription: Subscription; alertService: AlertService; constructor(alertService: AlertService) { this.alertService = alertService; } ngOnInit(): void { this.alertSubscription = this.alertService.onAlert(this.id).subscribe(alert =>{ if(!alert.message){ this.alerts = []; return; } this.alerts.push(alert); if(alert.autoClose){ setTimeout(() => this.removeAlert(alert),3000); } }); } ngOnDestroy() { this.alertSubscription.unsubscribe(); } removeAlert(alert: Alert){ if(!this.alerts.includes(alert)){ return; } if(alert.fade){ setTimeout(() => { this.alerts = this.alerts.filter(x => x!== alert); }, 250); } else { this.alerts = this.alerts.filter(x => x!= alert); } } alertsCssClass(alert: Alert){ if(!alert) return; const classes = ['alert','show','alert-dismissable']; const alertTypeClass = { [AlertType.Success]: 'alert alert-success', [AlertType.Error]: 'alert alert-danger', [AlertType.Info]: 'alert alert-info', [AlertType.Warning]: 'alert alert-warning' } classes.push(alertTypeClass[alert.type]); if(alert.fade){ classes.push('fade'); } return classes.join(' '); } } <file_sep>/src/app/user-management/create-user/create-user.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { CustomvalidationUtils } from 'src/app/common-utils/customvalidation.utils'; import { UserManagementService } from '../service/user-management.service'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { OverlayService } from 'src/app/common-utils/overlay.service'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; import { Router } from '@angular/router'; import { MytunesUtils } from 'src/app/common-utils/mytunes.utils'; import { forkJoin, Observable } from 'rxjs'; @Component({ selector: 'app-create-user', templateUrl: './create-user.component.html', styleUrls: ['./create-user.component.scss'] }) export class CreateUserComponent implements OnInit { userForm: FormGroup; formBuilder: FormBuilder userCityArray: object[]; cutomValidationUtils: CustomvalidationUtils; userManagementService: UserManagementService; alertService: AlertService; userRoles: object[]; cityData: object; overlayRef: OverlayRef; overlayService: OverlayService; router: Router; mytunesUtils: MytunesUtils; userDetails:object; genderValues: object[]; //move to filters mindate = new Date(); maxdate = new Date(); customDateFilter = (d: Date | null): boolean => { const date = (d || new Date()); this.mindate.setFullYear(1920,1,1); return date.getTime() >= this.mindate.getTime() && date.getTime()<this.maxdate.getTime(); } constructor(formBuilder: FormBuilder,cutomValidationUtils: CustomvalidationUtils,userManagementService: UserManagementService,alertService: AlertService,overlayService: OverlayService,router: Router,mytunesUtils:MytunesUtils) { this.formBuilder = formBuilder; this.userRoles = []; this.userCityArray = []; this.cutomValidationUtils = cutomValidationUtils; this.userManagementService = userManagementService; this.alertService = alertService; this.overlayService = overlayService; this.router = router; this.mytunesUtils = mytunesUtils; this.userDetails = {}; this.genderValues = []; } ngOnInit(): void { this.userForm = this.formBuilder.group({ username: ['',{ validators: [Validators.required,this.cutomValidationUtils.usernameValidator], asyncValidators: [this.cutomValidationUtils.duplicateuserValidator.bind(this.cutomValidationUtils)], updateOn: 'blur' }], usertype:['City Administrator',Validators.required], userCity:['',Validators.required], firstName:['',Validators.required], middleName:['',Validators.required], lastName:['',Validators.required], emailId:['',[Validators.required,Validators.email]], password:['',[Validators.required,this.cutomValidationUtils.passwordValidator]], confirmPassword:['',Validators.required], gender:['',Validators.required], phoneNumber:['',[Validators.required,this.cutomValidationUtils.phoneNumberValidator]], dateOfBirth:['',Validators.required], address:['',Validators.required] }, { validator: this.cutomValidationUtils.matchPassword('password','<PASSWORD>'), } ); this.loadGenderValues(); this.validateAndLoadUserDetails(); } loadGenderValues() { this.genderValues.push({'val':'Male','checked':false}); this.genderValues.push({'val':'Female','checked':false}); } loadUserCities() { let userCityObservable = this.userManagementService.fetchUserCities(); return userCityObservable; } loadUserRoles() { let userRolesObservable = this.userManagementService.fetchUserRoles(); return userRolesObservable; } onCityChange(selectedCityId){ let greyOutRole = false; for(let userRole in this.cityData){ if(this.cityData.hasOwnProperty(userRole) && (userRole === "City Administrator" || userRole === "Market Research Manager")){ let cityArr = this.cityData[userRole]; let cityFilter = cityArr.filter((cityObj) => cityObj.id == selectedCityId); if(cityFilter.length > 0 && userRole === "City Administrator"){ this.changeUserRole("Market Research Manager"); greyOutRole = true; this.userForm.get("usertype").disable(); this.userForm.get("usertype").updateValueAndValidity(); }else if(cityFilter.length > 0 && userRole === "Market Research Manager"){ this.changeUserRole("City Administrator"); greyOutRole = true; this.userForm.get("usertype").disable(); this.userForm.get("usertype").updateValueAndValidity(); } } } if(!greyOutRole){ this.userForm.get("usertype").enable(); this.userForm.get("usertype").updateValueAndValidity(); } } changeUserRole(userRole: string) { this.userRoles.forEach(userRoleObj => { if(userRoleObj["roleName"] == userRole){ this.userForm.get("usertype").setValue(userRoleObj["id"]); userRoleObj["checked"] = true; }else{ userRoleObj["checked"] = false; } }); } changeGender(gender: string) { this.genderValues.forEach(genderObj => { if(genderObj["val"] == gender){ this.userForm.get("gender").setValue(genderObj["name"]); genderObj["checked"] = true; }else{ genderObj["checked"] = false; } }); } createUser(){ if(this.userForm.valid){ console.log(this.userForm.value); let userVO = this.prepareUserData(); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.userManagementService.createUser(userVO).subscribe( success => { this.overlayRef.detach(); this.userManagementService.processCreateUserSuccessResponse(success); this.router.navigate(['/user/view']); this.alertService.success('User created successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.userManagementService.processCreateUserFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to create user.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } prepareUserData(){ let userVO: object = {}; userVO = JSON.parse(JSON.stringify(this.userForm.getRawValue())); let cityId = userVO["userCity"]; let roleId = userVO["usertype"]; delete userVO["confirmPassword"]; delete userVO["userCity"]; delete userVO["usertype"]; userVO["cityVO"] = {}; userVO["cityVO"]["id"]=cityId; userVO["userAuthorities"]= []; userVO["userAuthorities"].push({"id":roleId}); let dob: Date = new Date(userVO["dateOfBirth"]); let dobString = new Date(dob.getTime() - (dob.getTimezoneOffset() * 60000)).toISOString().split("T")[0]; userVO["dateOfBirth"] = dobString; console.log(JSON.stringify(userVO)); console.log(this.userForm.value); return userVO; } validateAndLoadUserDetails() { let userCityObservable = this.loadUserCities(); let userRolesObservable = this.loadUserRoles(); if(!this.userManagementService.userData){ userCityObservable.subscribe( success => { this.processGetUserCities(success); }, error => { const errorMessage = ""; //get error message from error object this.alertService.error('Failed to load user cities.',this.mytunesUtils.getAlertOptions(true,false,true)); }); userRolesObservable.subscribe( success => { this.processGetUserRoles(success); }, error => { const errorMessage = ""; //get error message from error object this.alertService.error('Failed to load user roles.',this.mytunesUtils.getAlertOptions(true,false,true)); }); return; } forkJoin(userCityObservable,userRolesObservable).subscribe(results=>{ this.processGetUserCities(results[0]); this.processGetUserRoles(results[1]); let userVO = JSON.parse(this.userManagementService.userData); userVO["confirmPassword"] = userVO["<PASSWORD>"]; userVO["usertype"] = userVO["userAuthorities"][0]["id"]; userVO["userCity"] = userVO["cityVO"]["id"]; Object.keys(this.userForm.controls).forEach(key => { this.userForm.controls[key].setValue(userVO[key]); }); this.userForm.get("username").disable(); this.userForm.get("password").disable(); this.userForm.get("confirmPassword").disable(); this.changeUserRole(userVO["userAuthorities"][0]["roleName"]); this.changeGender(userVO["gender"]); this.updateUserCityAndRoles(userVO["cityVO"]["id"]); this.userDetails = userVO; this.userManagementService.userData = ""; this.userForm.updateValueAndValidity(); }, errors => { if(errors[0]){ const errorMessage = ""; //get error message from error object this.alertService.error('Failed to load user cities.',this.mytunesUtils.getAlertOptions(true,false,true)); } if(errors[1]){ const errorMessage = ""; //get error message from error object this.alertService.error('Failed to load user roles.',this.mytunesUtils.getAlertOptions(true,false,true)); } }); } updateUserCityAndRoles(selectedCity: any) { if(this.userForm.controls["userCity"].value){ let selectedCityArr = this.userCityArray.filter(o => { if(o["id"] === this.userForm.controls["userCity"].value && o["disabled"]){ return true; } }); if(selectedCityArr.length != 0){ this.userForm.get("usertype").disable(); this.userForm.get("usertype").updateValueAndValidity(); } } } updateUser(){ if(true){ console.log(this.userForm.value); let userId = this.userDetails["id"]; let userVO = this.prepareUserData(); userVO["id"] = userId; userVO["createdDate"] = this.userDetails["createdDate"]; userVO["createdBy"] = this.userDetails["createdBy"]; userVO["accountLockedFlag"] = this.userDetails["accountLockedFlag"]; userVO["userEnabledFlag"] = this.userDetails["userEnabledFlag"]; console.log(JSON.stringify(userVO)); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.userManagementService.updateUser(userId,userVO).subscribe( success => { this.overlayRef.detach(); this.userManagementService.processUpdateUserSuccessResponse(success); this.router.navigate(['/user/view']); this.alertService.success('User updated successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.userManagementService.processUpdateUserFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to update user.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } processGetUserCities(cityResponse: any) { this.cityData = cityResponse; this.userCityArray = this.userManagementService.getFilteredCities(cityResponse); } processGetUserRoles(rolesResponse: any) { for(let i=0 ; i<rolesResponse.length;i++){ if(rolesResponse[i].roleName !== "India Administrator" && rolesResponse[i].roleName !== "Store Manager"){ let roleObj = {"id":rolesResponse[i].id,"roleName":rolesResponse[i].roleName,"checked":false}; if(rolesResponse[i].roleName === "City Administrator"){ this.userForm.get("usertype").setValue(rolesResponse[i].id); roleObj.checked = true; } this.userRoles.push(roleObj); } } } }<file_sep>/src/environments/environment.prod.ts export const environment = { production: true, //backendApiUrl: '${BACKEND_API_URL}' apiUrl:'http://172.16.17.32' // apiUrl:'http://localhost:8080' }; <file_sep>/src/app/auth-operations/login/login.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AuthService } from '../service/auth.service'; import { Router } from '@angular/router'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; import { OverlayRef } from '@angular/cdk/overlay'; import { OverlayService } from 'src/app/common-utils/overlay.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { overlayRef: OverlayRef; overlayService: OverlayService; loginForm: FormGroup; formBuilder: FormBuilder authService: AuthService; router: Router; showSpinner: boolean = false; alertService: AlertService; alertOptions = { autoClose: true, keepAfterRouteChange: false, fade: true }; constructor(formBuilder: FormBuilder,authService: AuthService,router: Router,alertService: AlertService,overlayService: OverlayService) { this.formBuilder = formBuilder; this.authService = authService; this.router = router; this.alertService = alertService; this.overlayService = overlayService; } ngOnInit(): void { this.loginForm = this.formBuilder.group({ username: ['', Validators.required], password: ['',Validators.required] }); } authenticateUser(){ if(this.loginForm.valid){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.showSpinner = true; this.authService.login(this.loginForm.controls["username"].value,this.loginForm.controls["password"].value).subscribe( success => { //success = {}; //success["response"] = JSON.parse('{"userAuthorities":[{"roleName":"India Administrator"}]}'); //success["jwtToken"] = "<KEY>"; this.overlayRef.detach(); this.authService.processSuccessLoginResponse(success); this.router.navigate(['/dashboard']); }, error => { this.overlayRef.detach(); this.authService.processFailureLoginResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Invalid credentials',this.alertOptions); } ); } } } <file_sep>/src/app/user-management/view-user/view-user.component.ts import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { UserManagementService } from '../service/user-management.service'; import { UserData } from '../model/user.data'; import * as _ from 'lodash'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { OverlayService } from 'src/app/common-utils/overlay.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { Router } from '@angular/router'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; import { MytunesUtils } from 'src/app/common-utils/mytunes.utils'; @Component({ selector: 'app-view-user', templateUrl: './view-user.component.html', styleUrls: ['./view-user.component.scss'] }) export class ViewUserComponent implements OnInit, AfterViewInit { @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; userManagementService: UserManagementService; columnObj: object; columns: string[] = ['firstName', 'lastName', 'emailId', 'phoneNumber', 'cityName', 'roleName','edit','delete']; dataSource: MatTableDataSource<UserData>; userDataArray: UserData[]; userObj: UserData; alertService: AlertService; overlayService: OverlayService; overlayRef: OverlayRef; router: Router; mytunesUtils: MytunesUtils; constructor(userManagementService: UserManagementService,alertService:AlertService,overlayService:OverlayService,router:Router,mytunesUtils:MytunesUtils) { this.userManagementService = userManagementService; this.columnObj = {}; this.userDataArray = []; this.dataSource = new MatTableDataSource(); this.alertService = alertService; this.overlayService = overlayService; this.router = router; this.mytunesUtils = mytunesUtils; } ngOnInit(): void { this.getAllUsers(); } ngAfterViewInit(): void { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } getAllUsers() { this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.userManagementService.getAllUsers().subscribe(success => { this.overlayRef.detach(); this.userDataArray = []; this.userDataArray = this.userDataArray.concat(success); this.userObj = this.userDataArray[0]; this.userDataArray.forEach(userVO => { userVO["cityName"] = userVO["cityVO"]["cityName"]; userVO["roleName"] = userVO["userAuthorities"][0]["roleName"]; }); this.dataSource = new MatTableDataSource(this.userDataArray); this.prepareColumnObject(); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; }, error => { this.overlayRef.detach(); this.userDataArray = []; this.dataSource = new MatTableDataSource(this.userDataArray); this.prepareColumnObject(); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; const errorMessage = "No users found."; //get error message from error object }); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } prepareColumnObject() { this.columns.forEach(column => { this.columnObj[column] = _.startCase(column); }); } editUser(userObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.userManagementService.getUserById(userObj["id"]).subscribe(success => { this.overlayRef.detach(); this.userManagementService.processEditUserSuccessResponse(success); this.router.navigate(['/user/create']); }, error => { this.overlayRef.detach(); this.alertService.error('Failed to load user details.',this.mytunesUtils.getAlertOptions(true,false,true)); const errorMessage = "Failed to load user."; //get error message from error object }); console.log(JSON.stringify(userObj)); } deleteUser(userObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.userManagementService.deleteUserById(userObj["id"]).subscribe(success => { this.overlayRef.detach(); this.getAllUsers(); this.alertService.success('User deleted successfully.',this.mytunesUtils.getAlertOptions(true,false,true)); }, error => { this.overlayRef.detach(); this.alertService.error('Failed to delete user.',this.mytunesUtils.getAlertOptions(true,false,true)); const errorMessage = "Failed to delete user."; //get error message from error object }); console.log(JSON.stringify(userObj)); } } <file_sep>/src/app/store-management/view-store/view-store.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { OverlayService } from 'src/app/common-utils/overlay.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { Router } from '@angular/router'; import { MytunesUtils } from 'src/app/common-utils/mytunes.utils'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; import * as _ from 'lodash'; import { StoreManagementService } from '../service/store-management.service'; @Component({ selector: 'app-view-store', templateUrl: './view-store.component.html', styleUrls: ['./view-store.component.scss'] }) export class ViewStoreComponent implements OnInit { @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; storeManagementService: StoreManagementService; columnObj: object; columns: string[] = ['storename', 'timings', 'capacity', 'cityName','storeManager','edit','delete']; dataSource: MatTableDataSource<Object>; storeDataArray: Object[]; storeObj: Object; alertService: AlertService; overlayService: OverlayService; overlayRef: OverlayRef; router: Router; mytunesUtils: MytunesUtils; constructor(storeManagementService: StoreManagementService,alertService:AlertService,overlayService:OverlayService,router:Router,mytunesUtils:MytunesUtils) { this.storeManagementService = storeManagementService; this.columnObj = {}; this.storeDataArray = []; this.dataSource = new MatTableDataSource(); this.alertService = alertService; this.overlayService = overlayService; this.router = router; this.mytunesUtils = mytunesUtils; } ngOnInit(): void { this.getAllStores(); } ngAfterViewInit(): void { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } getAllStores() { this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.getAllStores().subscribe(success => { this.overlayRef.detach(); this.storeDataArray = []; this.storeDataArray = this.storeDataArray.concat(success); this.storeObj = this.storeDataArray[0]; this.storeDataArray.forEach(storeVO => { storeVO["cityName"] = storeVO["cityVO"]["cityName"]; }); this.dataSource = new MatTableDataSource(this.storeDataArray); this.prepareColumnObject(); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; }, error => { this.overlayRef.detach(); this.storeDataArray = []; this.dataSource = new MatTableDataSource(this.storeDataArray); this.prepareColumnObject(); this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; const errorMessage = "No stores found."; //get error message from error object }); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } prepareColumnObject() { this.columns.forEach(column => { this.columnObj[column] = _.startCase(column); }); } editStore(storeObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.getStoreById(storeObj["id"]).subscribe(success => { this.overlayRef.detach(); this.storeManagementService.processEditStoreSuccessResponse(success); this.router.navigate(['/store/create']); }, error => { this.overlayRef.detach(); this.alertService.error('Failed to load store details.',this.mytunesUtils.getAlertOptions(true,false,true)); const errorMessage = "Failed to load store."; //get error message from error object }); console.log(JSON.stringify(storeObj)); } deleteStore(storeObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.deleteStoreById(storeObj["id"]).subscribe(success => { this.overlayRef.detach(); this.getAllStores(); this.alertService.success('Store deleted successfully.',this.mytunesUtils.getAlertOptions(true,false,true)); }, error => { this.overlayRef.detach(); this.alertService.error('Failed to delete store.',this.mytunesUtils.getAlertOptions(true,false,true)); const errorMessage = "Failed to delete store."; //get error message from error object }); console.log(JSON.stringify(storeObj)); } createStoreManager(storeObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); //pass store name and id details to storemanager component this.storeManagementService.storeData = JSON.stringify(storeObj); this.router.navigate(['/store/manager/create']); this.overlayRef.detach(); } editStoreManager(storeObj:Object){ this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.storeData = JSON.stringify(storeObj); this.router.navigate(['/store/manager/edit']); this.overlayRef.detach(); } } <file_sep>/src/app/store-management/service/store-management.service.spec.ts import { TestBed } from '@angular/core/testing'; import { StoreManagementService } from './store-management.service'; describe('StoreManagementService', () => { let service: StoreManagementService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(StoreManagementService); }); it('should be created', () => { expect(service).toBeTruthy(); }); }); <file_sep>/src/app/user-management/model/CityVO.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CityVO{ cityName:string; id:string; stateCode:string; createdBy:string; createdDate:Date; updatedBy:string; updatedDate:Date; constructor(){} public getCityName():string{ return this.cityName; } public setCityName(cityName:string){ this.cityName = cityName; } public getId():string{ return this.id; } public setId(id:string){ this.id = id; } public getStateCode():string{ return this.stateCode; } public setStateCode(stateCode:string){ this.stateCode = stateCode; } public getCreatedBy():string{ return this.createdBy; } public setCreatedBy(createdBy:string){ this.createdBy = createdBy; } public getUpdatedBy():string{ return this.updatedBy; } public setUpdatedBy(updatedBy:string){ this.updatedBy = updatedBy; } public getCreatedDate():Date{ return this.createdDate; } public setCreatedDate(createdDate:Date){ this.createdDate = createdDate; } public getUpdatedDate():Date{ return this.updatedDate; } public setUpdatedDate(updatedDate: Date){ this.updatedDate = updatedDate; } }<file_sep>/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { Route, RouterModule } from '@angular/router'; import { AuthguardService } from './auth-guard/authguard.service'; import { LogoutComponent } from './auth-operations/logout/logout.component'; const routes: Route[] = [ {path:'',redirectTo:'auth',pathMatch:'full'}, {path:'auth',loadChildren:'../app/auth-operations/auth-operations.module#AuthOperationsModule'}, {path:'user',loadChildren:'../app/user-management/user-management.module#UserManagementModule'}, {path:'store',loadChildren:'../app/store-management/store-management.module#StoreManagementModule'}, {path:'dashboard',loadChildren:'../app/dashboard/dashboard.module#DashboardModule',canActivate:[AuthguardService]}, {path:'logout',component:LogoutComponent,canActivate:[AuthguardService]}, {path: '**',redirectTo: 'auth'} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>/src/app/app.component.ts import { Component, OnInit, AfterViewInit } from '@angular/core'; import { AuthService } from './auth-operations/service/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit{ title = 'My Tunes'; authService: AuthService; isLoggedIn: boolean = false; currentUser: Object; userRole:string; router:Router; constructor(authService: AuthService,router:Router){ this.authService = authService; this.router = router; } ngOnInit(): void { this.isLoggedIn = this.authService.isAuthenticated(); //this.isLoggedIn = true; this.loadCurrentUser(); this.getCurrentUserRole(); let sub = this.authService.loginStatus$.subscribe((loggedInFlag)=>{ if(loggedInFlag){ this.isLoggedIn = this.authService.isAuthenticated(); this.loadCurrentUser(); this.getCurrentUserRole(); } }, error => { console.log(error); }); } logout(){ if(this.isLoggedIn){ this.isLoggedIn = false; this.authService.logout(); } } loadCurrentUser() { if(this.isLoggedIn){ this.currentUser = {}; //this.currentUser["firstName"] = "Varun"; this.currentUser = JSON.parse(localStorage.getItem("currentUser")); } } getCurrentUserRole() { if(this.isLoggedIn){ //this.userRole = "City Administrator"; this.userRole = this.currentUser["userAuthorities"][0]["roleName"]; } } } <file_sep>/Dockerfile # Stage 1 FROM node:10-alpine as build-stage RUN mkdir -p /app WORKDIR /app COPY package.json /app RUN npm install COPY . /app RUN npm run build --prod # Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx FROM nginx:1.15 #Copy ci-dashboard-dist COPY --from=build-stage /app/dist/mytunes-v3 /usr/share/nginx/html #Copy default nginx configuration COPY ./nginx-custom.conf /etc/nginx/conf.d/default.conf<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { FooterComponent } from './footer/footer.component'; import { HeaderComponent } from './header/header.component'; import { NavigationComponent } from './navigation/navigation.component'; import { UserManagementModule } from './user-management/user-management.module'; import { StoreManagementModule } from './store-management/store-management.module'; import { DashboardModule } from './dashboard/dashboard.module'; import { AlertsModule } from './alerts/alerts.module'; import { AuthOperationsModule } from './auth-operations/auth-operations.module'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { CustomvalidationUtils } from './common-utils/customvalidation.utils'; import { AuthguardService } from './auth-guard/authguard.service'; import { AuthService } from './auth-operations/service/auth.service'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { ErrorInterceptor } from './interceptors/error.interceptor'; import { JwtInterceptor } from './interceptors/jwt.interceptor'; import { JwtHelperService, JWT_OPTIONS } from '@auth0/angular-jwt'; import { MaterialModule } from './material/material.module'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AlertService } from './alerts/service/alert.service'; import { ProgressSpinnerComponent } from './progress-spinner/progress-spinner.component'; import { OverlayService } from './common-utils/overlay.service'; import { OverlayModule } from '@angular/cdk/overlay'; @NgModule({ declarations: [ AppComponent, FooterComponent, HeaderComponent, NavigationComponent, ProgressSpinnerComponent ], imports: [ BrowserModule, AppRoutingModule, UserManagementModule, StoreManagementModule, DashboardModule, AlertsModule, AuthOperationsModule, FormsModule, ReactiveFormsModule, HttpClientModule, MaterialModule, BrowserAnimationsModule, OverlayModule ], providers: [ CustomvalidationUtils, AuthguardService, AuthService, { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, JwtHelperService, { provide: JWT_OPTIONS, useValue: JWT_OPTIONS }, AlertService, OverlayService ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/store-management/store-manager/store-manager.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { CustomvalidationUtils } from 'src/app/common-utils/customvalidation.utils'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { OverlayService } from 'src/app/common-utils/overlay.service'; import { Router } from '@angular/router'; import { MytunesUtils } from 'src/app/common-utils/mytunes.utils'; import { StoreManagementService } from '../service/store-management.service'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; @Component({ selector: 'app-store-manager', templateUrl: './store-manager.component.html', styleUrls: ['./store-manager.component.scss'] }) export class StoreManagerComponent implements OnInit { storeManagerForm: FormGroup; formBuilder: FormBuilder cityArray: object[]; cutomValidationUtils: CustomvalidationUtils; storeManagementService: StoreManagementService; alertService: AlertService; overlayRef: OverlayRef; overlayService: OverlayService; router: Router; mytunesUtils: MytunesUtils; userDetails:object; genderValues: object[]; storeId:string; //move to filters mindate = new Date(); maxdate = new Date(); customDateFilter = (d: Date | null): boolean => { const date = (d || new Date()); this.mindate.setFullYear(1920,1,1); return date.getTime() >= this.mindate.getTime() && date.getTime()<this.maxdate.getTime(); } constructor(formBuilder: FormBuilder,cutomValidationUtils: CustomvalidationUtils,storeManagementService: StoreManagementService,alertService: AlertService,overlayService: OverlayService,router: Router,mytunesUtils:MytunesUtils) { this.formBuilder = formBuilder; this.cityArray = []; this.cutomValidationUtils = cutomValidationUtils; this.storeManagementService = storeManagementService; this.alertService = alertService; this.overlayService = overlayService; this.router = router; this.mytunesUtils = mytunesUtils; this.userDetails = {}; this.genderValues = []; } ngOnInit(): void { this.storeManagerForm = this.formBuilder.group({ username: ['',{ validators: [Validators.required,this.cutomValidationUtils.usernameValidator], asyncValidators: [this.cutomValidationUtils.duplicateuserValidator.bind(this.cutomValidationUtils)], updateOn: 'blur' }], userCity:['',Validators.required], firstName:['',Validators.required], storename:['',Validators.required], middleName:['',Validators.required], lastName:['',Validators.required], emailId:['',[Validators.required,Validators.email]], password:['',[Validators.required,this.cutomValidationUtils.passwordValidator]], confirmPassword:['',Validators.required], gender:['',Validators.required], phoneNumber:['',[Validators.required,this.cutomValidationUtils.phoneNumberValidator]], dateOfBirth:['',Validators.required], address:['',Validators.required] }, { validator: this.cutomValidationUtils.matchPassword('<PASSWORD>','<PASSWORD>'), } ); this.loadGenderValues(); this.loadUserCity(); this.validateAndLoadUserDetails(); } validateAndLoadUserDetails() { if(this.storeManagementService.storeData && !this.storeManagementService.storeData["storeManagerVO"]){ let storeVO = JSON.parse(this.storeManagementService.storeData); this.storeManagerForm.controls["storename"].setValue(storeVO["storename"]); this.storeId = storeVO["id"]; this.storeManagementService.storeData = ""; } if(this.storeManagementService.storeData && this.storeManagementService.storeData["storeManagerVO"]){ let storeVO = JSON.parse(this.storeManagementService.storeData); let userVO = storeVO["storeManagerVO"]; this.storeId = storeVO["id"]; userVO["confirmPassword"] = userVO["<PASSWORD>"]; userVO["storeName"] = storeVO["storeName"]; Object.keys(this.storeManagerForm.controls).forEach(key => { this.storeManagerForm.controls[key].setValue(userVO[key]); }); this.storeManagerForm.get("username").disable(); this.storeManagerForm.get("password").disable(); this.storeManagerForm.get("confirmPassword").disable(); this.changeGender(userVO["gender"]); this.userDetails = userVO; this.storeManagementService.storeData = ""; this.storeManagerForm.updateValueAndValidity(); } } loadGenderValues() { this.genderValues.push({'val':'Male','checked':false}); this.genderValues.push({'val':'Female','checked':false}); } loadUserCity() { let currentUser = JSON.parse(localStorage.getItem("currentUser")); //currentUser = {}; //currentUser["id"] = "1234"; //currentUser["cityVO"] = {}; //currentUser["cityVO"]["cityName"] = "Dharwad"; let cityObj = {}; cityObj["id"] = currentUser["cityVO"]["id"]; cityObj["cityName"] = currentUser["cityVO"]["cityName"]; cityObj["disabled"] = true; this.cityArray.push(cityObj); this.storeManagerForm.get("userCity").setValue(cityObj["id"]); this.storeManagerForm.get("userCity").disable(); this.storeManagerForm.updateValueAndValidity(); } changeGender(gender: string) { this.genderValues.forEach(genderObj => { if(genderObj["val"] == gender){ this.storeManagerForm.get("gender").setValue(genderObj["name"]); genderObj["checked"] = true; }else{ genderObj["checked"] = false; } }); } createStoreManager(){ if(this.storeManagerForm.valid){ console.log(this.storeManagerForm.value); let userVO = this.prepareUserData(); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.createStoreManager(this.storeId,userVO).subscribe( success => { this.overlayRef.detach(); this.storeManagementService.processCreateStoreManagerSuccessResponse(success); this.router.navigate(['/store/view']); this.alertService.success('Store manager created successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.storeManagementService.processCreateStoreManagerFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to create store manager.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } prepareUserData(){ let userVO: object = {}; userVO = JSON.parse(JSON.stringify(this.storeManagerForm.getRawValue())); let cityId = userVO["userCity"]; delete userVO["confirmPassword"]; delete userVO["storeName"]; delete userVO["confirmPassword"]; delete userVO["userCity"]; userVO["cityVO"] = {}; userVO["cityVO"]["id"]=cityId; let dob: Date = new Date(userVO["dateOfBirth"]); let dobString = new Date(dob.getTime() - (dob.getTimezoneOffset() * 60000)).toISOString().split("T")[0]; userVO["dateOfBirth"] = dobString; console.log(JSON.stringify(userVO)); console.log(this.storeManagerForm.value); return userVO; } updateStoreManager(){ if(true){ console.log(this.storeManagerForm.value); let userId = this.userDetails["id"]; let userVO = this.prepareUserData(); userVO["id"] = userId; userVO["createdDate"] = this.userDetails["createdDate"]; userVO["createdBy"] = this.userDetails["createdBy"]; userVO["accountLockedFlag"] = this.userDetails["accountLockedFlag"]; userVO["userEnabledFlag"] = this.userDetails["userEnabledFlag"]; console.log(JSON.stringify(userVO)); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.updateStoreManager(userId,this.storeId,userVO).subscribe( success => { this.overlayRef.detach(); this.storeManagementService.processUpdateUserSuccessResponse(success); this.router.navigate(['/store/view']); this.alertService.success('User updated successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.storeManagementService.processUpdateUserFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to update user.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } } <file_sep>/src/app/alerts/service/alert.service.ts import { Injectable } from '@angular/core'; import { Observable, Subject, Subscription } from 'rxjs'; import { Alert, AlertType } from '../model/Alert'; import { filter } from 'rxjs/operators'; import { Router, NavigationStart, NavigationEnd } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AlertService { private subject = new Subject<Alert>(); private defaultId = "default-alert"; private keepAfterRouteChange: boolean = false routeSubscription: Subscription; router: Router; constructor(router:Router) { this.router = router; this.routeSubscription = this.router.events.subscribe( event => { if(event instanceof NavigationEnd){ if(this.keepAfterRouteChange){ //only keep for a single route change this.keepAfterRouteChange = false; }else{ //clear alert message //setTimeout(() => this.clear(this.defaultId),5000); this.clear(this.defaultId); } } }); } onAlert(id = this.defaultId): Observable<Alert> { return this.subject.asObservable().pipe(filter(x => x && x.id === id)); } success(message: string,options?: any){ this.keepAfterRouteChange = options.keepAfterRouteChange; this.alert(new Alert({...options,type: AlertType.Success,message})); } error(message: string,options?: any){ this.keepAfterRouteChange = options.keepAfterRouteChange; this.alert(new Alert({...options,type: AlertType.Error,message})); } info(message: string,options?: any){ this.keepAfterRouteChange = options.keepAfterRouteChange; this.alert(new Alert({...options,type: AlertType.Info,message})); } warn(message: string,options?: any){ this.keepAfterRouteChange = options.keepAfterRouteChange; this.alert(new Alert({...options,type: AlertType.Warning,message})); } alert(alert: Alert){ alert.id = alert.id || this.defaultId; this.subject.next(alert); } clear(id = this.defaultId) { this.subject.next(new Alert({ id })); //this.subject.next(); } } <file_sep>/src/app/store-management/service/store-management.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class StoreManagementService { httpClient: HttpClient; storeData: string; constructor(httpClient: HttpClient) { this.httpClient = httpClient; } validateDuplicateStore(storename: any) { return this.httpClient.post<any>('/storemanagement/stores/duplicatestore/'+storename,null); } createStore(storeData) { return this.httpClient.post<any>('/storemanagement/stores',storeData); } getAllStores() { return this.httpClient.get<any>('/storemanagement/stores'); } getStoreById(storeId:string) { return this.httpClient.get<any>('/storemanagement/stores/id/'+storeId); } deleteStoreById(storeId:string) { return this.httpClient.delete<any>('/storemanagement/stores/'+storeId); } updateStore(storeId: any, storeVO: object) { return this.httpClient.put<any>('/storemanagement/stores/'+storeId,storeVO); } createStoreManager(storeId: string,userVO: object) { return this.httpClient.post<any>('/storemanagement/stores/'+storeId+'/manager',userVO); } updateStoreManager(managerId: string, storeId: string, userVO: object) { return this.httpClient.post<any>('/storemanagement/stores/'+storeId+'/manager'+managerId,userVO); } processCreateStoreSuccessResponse(success: any) { console.log(success); } processCreateStoreFailureResponse(error: any) { console.log(error); } processEditStoreSuccessResponse(success: any) { this.storeData = JSON.stringify(success); } processUpdateStoreFailureResponse(error: any) { } processUpdateStoreSuccessResponse(success: any) { } processCreateStoreManagerSuccessResponse(success: any) { throw new Error("Method not implemented."); } processCreateStoreManagerFailureResponse(error: any) { throw new Error("Method not implemented."); } processUpdateUserSuccessResponse(success: any) { throw new Error("Method not implemented."); } processUpdateUserFailureResponse(error: any) { throw new Error("Method not implemented."); } } <file_sep>/src/app/common-utils/customvalidation.utils.ts import { Injectable } from '@angular/core'; import { AbstractControl, FormGroup, ValidationErrors } from '@angular/forms'; import { UserManagementService } from '../user-management/service/user-management.service'; import { Observable } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { StoreManagementService } from '../store-management/service/store-management.service'; @Injectable({ providedIn: 'root' }) export class CustomvalidationUtils { userManagementService: UserManagementService; storeManagementService: StoreManagementService; constructor(userManagementService: UserManagementService,storeManagementService: StoreManagementService) { this.userManagementService = userManagementService; this.storeManagementService = storeManagementService; } passwordValidator(control: AbstractControl): {[key: string]:any} | null{ const passwordRegex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$'); const passwordValidFlag: boolean = passwordRegex.test(control.value); if(!control.value){ return null; } return passwordValidFlag ? null : {invalidPassword:true}; } phoneNumberValidator(control: AbstractControl): {[key: string]:any} | null{ const phoneNumberRegex = new RegExp('[6-9]{1}[0-9]{9}'); const phoneNumberValidFlag: boolean = phoneNumberRegex.test(control.value); if(!control.value){ return null; } return phoneNumberValidFlag ? null : {invalidPhoneNumber:true}; } matchPassword(password: string,confirmPassword: string){ return (formGroup: FormGroup) =>{ const passwordControl = formGroup.controls[password]; const confirmPasswordControl = formGroup.controls[confirmPassword]; if(!passwordControl || !confirmPasswordControl){ return null; } if(confirmPasswordControl.errors && !confirmPasswordControl.errors.passwordMismatch){ return null; } if(passwordControl.value !== confirmPasswordControl.value){ confirmPasswordControl.setErrors({passwordMismatch: true}); }else{ confirmPasswordControl.setErrors(null); } }; } usernameValidator(control: AbstractControl): {[key: string]:any} | null{ const username = control.value; const usernameRegex = new RegExp('^(?=[a-z_\d]*[a-z])[a-z_\d]{6,30}$'); const usernameValidFlag: boolean = usernameRegex.test(username); if(!control.value){ return null; } return usernameValidFlag ? null : {invalidUsername:true}; } duplicateuserValidator(control: AbstractControl): Observable<ValidationErrors | null>{ const username = control.value; const usernameRegex = new RegExp('^(?=[a-z_\d]*[a-z])[a-z_\d]{6,30}$'); const usernameValidFlag: boolean = usernameRegex.test(username); if(!control.value){ return null; } if(usernameValidFlag){ //change the response to 200 and boolean true/false return this.userManagementService.validateDuplicateUser(username).pipe( map(res => { console.log(res); return res.DUPLICATE_USER_FLAG ? {duplicateUsername:true} : null; }), catchError(err => { console.log(err); return null; }) ); } } storenameValidator(control: AbstractControl): {[key: string]:any} | null{ const storename = control.value; const storenameRegex = new RegExp('^[a-zA-Z0-9]{6,20}$'); const storenameValidFlag: boolean = storenameRegex.test(storename); if(!control.value){ return null; } return storenameValidFlag ? null : {invalidStorename:true}; } duplicateStoreValidator(control: AbstractControl): Observable<ValidationErrors | null>{ const storename = control.value; const storenameRegex = new RegExp('^[a-zA-Z0-9]{6,20}$'); const storenameValidFlag: boolean = storenameRegex.test(storename); if(!control.value){ return null; } if(storenameValidFlag){ return this.storeManagementService.validateDuplicateStore(storename).pipe( map(res => { console.log(res); return res.DUPLICATE_STORE_FLAG ? {duplicateStorename:true} : null; }), catchError(err => { console.log(err); return null; }) ); } } } <file_sep>/src/app/auth-operations/register/register.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { CustomvalidationUtils } from 'src/app/common-utils/customvalidation.utils'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent implements OnInit { registerForm: FormGroup; formBuilder: FormBuilder; cutomValidationUtils: CustomvalidationUtils; constructor(formBuilder: FormBuilder,cutomValidationService: CustomvalidationUtils) { this.formBuilder = formBuilder; this.cutomValidationUtils = cutomValidationService; } ngOnInit(): void { this.registerForm = this.formBuilder.group({ firstName:['',Validators.required], lastName:['',Validators.required], username:['',Validators.required], email:['',[Validators.required,Validators.email]], password:['',[Validators.required,this.cutomValidationUtils.passwordValidator]], confirmPassword:['',Validators.required] }, { validator: this.cutomValidationUtils.matchPassword('password','<PASSWORD>'), } ); } registerUser(){ console.log("Form validated successfully!"); } } <file_sep>/src/app/common-utils/mytunes.utils.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MytunesUtils{ getAlertOptions(autoCloseOption:boolean,keepAfterRouteChangeOption:boolean,fadeOption:boolean){ let alertOptions = { autoClose: autoCloseOption, keepAfterRouteChange: keepAfterRouteChangeOption, fade: fadeOption }; return alertOptions; } }<file_sep>/src/app/store-management/store-management-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule, Route } from '@angular/router'; import { CreateStoreComponent } from './create-store/create-store.component'; import { ViewStoreComponent } from './view-store/view-store.component'; import { StoreManagerComponent } from './store-manager/store-manager.component'; const routes: Route[] = [ {path:'',redirectTo:'dashboard',pathMatch:'full'}, {path:'create',component:CreateStoreComponent}, {path:'view',component:ViewStoreComponent}, {path:'manager/create',component:StoreManagerComponent}, {path:'manager/edit',component:StoreManagerComponent} ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class StoreManagementRoutingModule { } <file_sep>/src/app/user-management/model/user.data.ts import { Injectable } from '@angular/core'; import { CityVO } from './CityVO'; import { RoleVO } from "./RoleVO"; @Injectable({ providedIn: 'root' }) export class UserData{ private id: string; private firstName: string; private lastName: string; private phoneNumber: number; private middleName: string; private gender: string; private dateOfBirth: Date; private username: string; private password: string; private emailId: string; private cityVO: CityVO; private userAuthorities: Set<RoleVO>; private address: string; private accountLockedFlag: string; private userEnabledFlag: string; private cityId: string; private roleIdList: string[]; constructor(){} public getId(): string { return this.id; } public setId(id: string) { this.id = id; } public getFirstName(): string { return this.firstName; } public setFirstName(firstName: string) { this.firstName = firstName; } public getLastName(): string { return this.lastName; } public setLastName(lastName: string) { this.lastName = lastName; } public getPhoneNumber(): number { return this.phoneNumber; } public setPhoneNumber(phoneNumber: number) { this.phoneNumber = phoneNumber; } public getMiddleName(): string { return this.middleName; } public setMiddleName(middleName: string) { this.middleName = middleName; } public getGender(): string { return this.gender; } public setGender(gender: string) { this.gender = gender; } public getDateOfBirth(): Date { return this.dateOfBirth; } public setDateOfBirth(dateOfBirth: Date) { this.dateOfBirth = dateOfBirth; } public getUsername(): string { return this.username; } public setUsername(username: string) { this.username = username; } public getPassword(): string { return this.password; } public setPassword(password: string) { this.password = <PASSWORD>; } public getEmailId(): string { return this.emailId; } public setEmailId(emailId: string) { this.emailId = emailId; } public getCityVO(): CityVO { return this.cityVO; } public setCityVO(cityVO: CityVO) { this.cityVO = cityVO; } public getUserAuthorities(): Set<RoleVO> { return this.userAuthorities; } public setUserAuthorities(userAuthorities: Set<RoleVO>) { this.userAuthorities = userAuthorities; } public getAddress(): string { return this.address; } public setAddress(address: string) { this.address = address; } public getAccountLockedFlag(){ return this.accountLockedFlag; } public setAccountLockedFlag(accountLockedFlag: string){ this.accountLockedFlag = accountLockedFlag; } public getUserEnabledFlag(){ return this.userEnabledFlag; } public setUserEnabledFlag(userEnabledFlag: string){ this.userEnabledFlag = userEnabledFlag; } public getCityId(){ return this.cityId; } public setCityId(cityId: string){ this.cityId = cityId; } public getRoleIdList(){ return this.roleIdList; } public setRoleIdList(roleIdList: string[]){ this.roleIdList = roleIdList; } }<file_sep>/src/app/progress-spinner/progress-spinner.component.ts import { Component, OnInit, Input } from '@angular/core'; import { OverlayService } from '../common-utils/overlay.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal'; @Component({ selector: 'app-progress-spinner', templateUrl: './progress-spinner.component.html', styleUrls: ['./progress-spinner.component.scss'] }) export class ProgressSpinnerComponent implements OnInit { @Input() showSpinner: boolean = false; @Input() backdropEnabled: boolean = false; overlayService: OverlayService; overlayRef: OverlayRef; constructor(overlayService: OverlayService) { this.overlayService = overlayService; } ngOnInit(): void { this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); } ngDoCheck() { // Based on status of displayProgressSpinner attach/detach overlay to progress spinner template if (this.showSpinner && !this.overlayRef.hasAttached()) { const componentPortal = new ComponentPortal(ProgressSpinnerComponent); this.overlayRef.attach(componentPortal); } else if (!this.showSpinner && this.overlayRef.hasAttached()) { this.overlayRef.detach(); } } } <file_sep>/src/app/user-management/service/user-management.service.ts import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class UserManagementService { httpClient: HttpClient; router: Router; userData:string; constructor(httpClient: HttpClient,router:Router) { this.httpClient = httpClient; this.router = router; } getFilteredCities(userCityResponse: any) { let userCity: object[] = []; if(userCityResponse.hasOwnProperty("ANONYMOUS") ){ userCity = userCity.concat(userCityResponse.ANONYMOUS); } if(userCityResponse.hasOwnProperty("City Administrator") && userCityResponse.hasOwnProperty("Market Research Manager")){ let indiaAdminCityFlag = false; let cityArr1 = userCityResponse["City Administrator"]; let cityArr2 = userCityResponse["Market Research Manager"]; let unique1 = cityArr1.filter(o1 => cityArr2.some(o2 => o1.cityName !== o2.cityName)); let unique2 = cityArr2.filter(o1 => cityArr1.some(o2 => o1.cityName !== o2.cityName)); let uniqueCityArr = unique1.concat(unique2); userCity = userCity.concat(uniqueCityArr); let common = cityArr1.filter(o1 => cityArr2.some(o2 => o1.cityName === o2.cityName)); common.forEach(city => { city["disabled"]=true; userCity.push(city); if(city.cityName === userCityResponse["India Administrator"][0].cityName){ indiaAdminCityFlag = true; } }); if(!indiaAdminCityFlag){ userCity = userCity.concat(userCityResponse["India Administrator"]); } } else if(userCityResponse.hasOwnProperty("City Administrator") || userCityResponse.hasOwnProperty("Market Research Manager")){ let cityArr1 = userCityResponse["City Administrator"]; let cityArr2 = userCityResponse["Market Research Manager"]; if(cityArr1){ userCity = userCity.concat(cityArr1); } if(cityArr2){ userCity = userCity.concat(cityArr2); } userCity = userCity.concat(userCityResponse["India Administrator"]); } else { userCity = userCity.concat(userCityResponse["India Administrator"]); } return userCity; } fetchUserCities() { return this.httpClient.get<any>('/usermanagement/users/citybyroles'); } fetchUserRoles() { return this.httpClient.get<any>('/usermanagement/users/roles'); } createUser(userData) { return this.httpClient.post<any>('/usermanagement/users',userData); } validateDuplicateUser(username: string) { return this.httpClient.post<any>('/usermanagement/users/duplicateuser/'+username,null); } processCreateUserSuccessResponse(success: any) { console.log(success); } processCreateUserFailureResponse(error: any) { console.log(error); } getAllUsers() { return this.httpClient.get<any>('/usermanagement/users'); } getUserById(userId:string) { return this.httpClient.get<any>('/usermanagement/users/id/'+userId); } processEditUserSuccessResponse(success: any) { this.userData = JSON.stringify(success); } deleteUserById(userId:string) { return this.httpClient.delete<any>('/usermanagement/users/'+userId); } processUpdateUserFailureResponse(error: any) { throw new Error("Method not implemented."); } processUpdateUserSuccessResponse(success: any) { } updateUser(userId: any, userVO: object) { return this.httpClient.put<any>('/usermanagement/users/'+userId,userVO); } } <file_sep>/src/app/user-management/model/RoleVO.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class RoleVO { id:string; roleName:string; createdBy:string; createdDate:Date; updatedBy:string; updatedTime:Date; public getCreatedBy():string{ return this.createdBy; } public setCreatedBy(createdBy:string){ this.createdBy = createdBy; } public getUpdatedBy():string{ return this.updatedBy; } public setUpdatedBy(updatedBy:string){ this.updatedBy = updatedBy; } public getCreatedDate():Date{ return this.createdDate; } public setCreatedDate(createdDate:Date){ this.createdDate = createdDate; } public getUpdatedDate():Date{ return this.updatedTime; } public setUpdatedTime(updatedTime: Date){ this.updatedTime = updatedTime; } } <file_sep>/src/app/interceptors/jwt.interceptor.ts import { HttpRequest,HttpHandler,HttpEvent,HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class JwtInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { let token = localStorage.getItem("token"); let currentUser = JSON.parse(localStorage.getItem("currentUser")); if(currentUser && token){ request = request.clone({headers: request.headers.set('Authorization', 'Bearer '+ token)}); request = request.clone({headers: request.headers.set('Content-Type','application/json')}); } //let success = {}; //success["response"] = JSON.parse('{"userAuthorities":[{"roleName":"India Administrator"}]}'); //success["jwtToken"] = "<KEY>"; //return of(new HttpResponse({ status: 200, body: ((success) as any).default })); return next.handle(request); } }<file_sep>/src/app/auth-operations/service/auth.service.ts import { Inject, Injectable } from '@angular/core'; import { JwtHelperService } from '@auth0/angular-jwt'; import { HttpClient } from '@angular/common/http'; import { Observable, Subject } from 'rxjs'; import { Router } from '@angular/router'; import { environment } from 'src/environments/environment.prod'; @Injectable({ providedIn: 'root' }) export class AuthService { jwtHelperService: JwtHelperService; httpClient: HttpClient; router: Router; apiUrl = environment.apiUrl; private _statusChange$: Subject<Boolean>; public loginStatus$: Observable<any>; constructor(jwtHelperService: JwtHelperService,httpClient: HttpClient,router:Router) { this.jwtHelperService = jwtHelperService; this.httpClient = httpClient; this.router = router; this._statusChange$ = new Subject<Boolean>(); this.loginStatus$ = this._statusChange$.asObservable(); } public isAuthenticated(): boolean{ const token = localStorage.getItem("token"); const currentUser = localStorage.getItem("currentUser"); if(!token || !currentUser){ return false; } /*if(this.jwtHelperService.isTokenExpired(token)){ return false; }*/ return true; } public login(username: string,password: string): Observable<any>{ return this.httpClient.post<any>(this.apiUrl+'/authmanagement/auth/login',{username: username, password: <PASSWORD>}); } public processFailureLoginResponse(errorResponse: any) { if(errorResponse){ console.log(JSON.stringify(errorResponse)); } } public processSuccessLoginResponse(successResponse: any) { if(successResponse){ console.log(JSON.stringify(successResponse)); localStorage.setItem('currentUser',JSON.stringify(successResponse.response)); localStorage.setItem('token',successResponse.jwtToken); this._statusChange$.next(true); } } public logout(){ localStorage.clear(); this._statusChange$.next(false); this.router.navigate(['/auth/login']); } } <file_sep>/src/app/store-management/create-store/create-store.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { CustomvalidationUtils } from 'src/app/common-utils/customvalidation.utils'; import { StoreManagementService } from '../service/store-management.service'; import { AlertService } from 'src/app/alerts/service/alert.service'; import { OverlayRef } from '@angular/cdk/overlay'; import { OverlayService } from 'src/app/common-utils/overlay.service'; import { Router } from '@angular/router'; import { MytunesUtils } from 'src/app/common-utils/mytunes.utils'; import { ProgressSpinnerComponent } from 'src/app/progress-spinner/progress-spinner.component'; @Component({ selector: 'app-create-store', templateUrl: './create-store.component.html', styleUrls: ['./create-store.component.scss'] }) export class CreateStoreComponent implements OnInit { storeForm: FormGroup; formBuilder: FormBuilder cutomValidationUtils: CustomvalidationUtils; storeManagementService: StoreManagementService; alertService: AlertService; overlayRef: OverlayRef; overlayService: OverlayService; router: Router; mytunesUtils: MytunesUtils; cityArr:Object[]; storeDetails:Object[]; constructor(formBuilder: FormBuilder,cutomValidationUtils: CustomvalidationUtils,storeManagementService: StoreManagementService,alertService: AlertService,overlayService: OverlayService,router: Router,mytunesUtils:MytunesUtils) { this.formBuilder = formBuilder; this.cutomValidationUtils = cutomValidationUtils; this.storeManagementService = storeManagementService; this.alertService = alertService; this.overlayService = overlayService; this.router = router; this.mytunesUtils = mytunesUtils; this.cityArr = []; } ngOnInit(): void { this.storeForm = this.formBuilder.group({ storename: ['',{ validators: [Validators.required,this.cutomValidationUtils.storenameValidator], asyncValidators: [this.cutomValidationUtils.duplicateStoreValidator.bind(this.cutomValidationUtils)], updateOn: 'blur' }], //storename: ['',[Validators.required,this.cutomValidationUtils.storenameValidator]], storeCity:['',Validators.required], timings:['',Validators.required], capacity:['',Validators.required], emailId:['',[Validators.required,Validators.email]], phoneNumber:['',[Validators.required,this.cutomValidationUtils.phoneNumberValidator]], address:['',Validators.required] } ); this.loadUserCity(); this.loadStoreDetails(); } loadUserCity() { let currentUser = JSON.parse(localStorage.getItem("currentUser")); //currentUser = {}; //currentUser["id"] = "1234"; //currentUser["cityVO"] = {}; //currentUser["cityVO"]["cityName"] = "Dharwad"; let cityObj = {}; cityObj["id"] = currentUser["cityVO"]["id"]; cityObj["cityName"] = currentUser["cityVO"]["cityName"]; cityObj["disabled"] = true; this.cityArr.push(cityObj); this.storeForm.get("storeCity").setValue(cityObj["id"]); this.storeForm.get("storeCity").disable(); this.storeForm.updateValueAndValidity(); } createStore(){ if(this.storeForm.valid){ console.log(this.storeForm.value); let storeVO = this.prepareStoreData(); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.createStore(storeVO).subscribe( success => { this.overlayRef.detach(); this.storeManagementService.processCreateStoreSuccessResponse(success); this.router.navigate(['/store/view']); this.alertService.success('Store created successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.storeManagementService.processCreateStoreFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to create store.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } prepareStoreData() { let storeVO: object = {}; storeVO = JSON.parse(JSON.stringify(this.storeForm.getRawValue())); let cityId = storeVO["storeCity"]; delete storeVO["storeCity"]; storeVO["cityVO"] = {}; storeVO["cityVO"]["id"]=cityId; console.log(JSON.stringify(storeVO)); console.log(this.storeForm.value); return storeVO; } loadStoreDetails() { if(!this.storeManagementService.storeData){ return; } let storeVO = JSON.parse(this.storeManagementService.storeData); storeVO["storeCity"] = storeVO["cityVO"]["id"]; Object.keys(this.storeForm.controls).forEach(key => { this.storeForm.controls[key].setValue(storeVO[key]); }); this.storeForm.updateValueAndValidity(); this.storeDetails = storeVO; this.storeManagementService.storeData = ""; } updateStore(){ if(true){ console.log(this.storeForm.value); let storeId = this.storeDetails["id"]; let storeVO = this.prepareStoreData(); storeVO["id"] = storeId; storeVO["createdDate"] = this.storeDetails["createdDate"]; storeVO["createdBy"] = this.storeDetails["createdBy"]; storeVO["updatedBy"] = this.storeDetails["createdBy"]; //if store details has city and manager details then update JSON console.log(JSON.stringify(storeVO)); this.overlayRef = this.overlayService.open({ hasBackdrop: true }, ProgressSpinnerComponent); this.storeManagementService.updateStore(storeId,storeVO).subscribe( success => { this.overlayRef.detach(); this.storeManagementService.processUpdateStoreSuccessResponse(success); this.router.navigate(['/store/view']); this.alertService.success('Store updated successfully.',this.mytunesUtils.getAlertOptions(false,true,true)); }, error => { this.overlayRef.detach(); this.storeManagementService.processUpdateStoreFailureResponse(error); const errorMessage = ""; //get error message from error object this.alertService.error('Failed to update store.',this.mytunesUtils.getAlertOptions(true,false,true)); } ); } } }
9e04d6c73b30c30604a12cb826b0c622f4267c4c
[ "TypeScript", "Dockerfile" ]
27
TypeScript
varunpadaki/mytunes-angular-ui
40e4c0612385bcf77684f9cccf1809a20d19e3c6
d7380d54b3f6e8ca11778b5b7f45179f23afd565
refs/heads/master
<file_sep>var fs = require('fs'); var options = { key: fs.readFileSync('/keys/<KEY>'), cert: fs.readFileSync('/certs/40adb2ebbbf524809cb4d9396fb6.crt') }; var http = require('https').createServer(options); var io = require('socket.io').listen(http, {origins:'*:*'}); var db = require('mysql2'); http.listen(1111, function(){ console.log('listening on *:1111'); }); var connection = db.createConnection({ host : '', user : '', password : '', database : '' }); connection.connect(function(err){ if (err) { return console.error("Ошибка: " + err.message); } else { console.log("Подключение к MySQL установлено"); } }); var users_login_list = {}; var user_ids = []; var arrUserslist = {}; io.on('connection', function(socket) { connection.query('SET NAMES utf8mb4', function(err, res) { if(err) console.log(err); }); /*---------------LOGIN USER, ADD BTNONLINE, DISCONNECT USER, DELETE BTNONLINE-----------*/ socket.on('login', function(id_user_login) { //принимаем id пользователя который должен аторизоваться connection.query('update tori_users set onlineSatus = ?, socketid = ? where id = ?', [1, socket.id, id_user_login], function (err, res) { if(err) console.log(err); else { connection.query('select id, login from users where id = ?', [id_user_login], function(err, login){ io.emit('createBtnChat', {id: id_user_login, login: login[0].login}); user_ids.push(id_user_login); //позволяет добавить один, или более элементов в конец массива socket.user_id = id_user_login; users_login_list[id_user_login] = socket.id; ifUserOnline(socket.user_id); }); } }); }); socket.on('ifAuthorOnline', function(id_author) { ifUserOnline(id_author); }); socket.on('disconnect', function () { setTimeout(function () { connection.query('update users set onlineSatus = ?, socketid = NULL where socketid = ?', [0, socket.id], function (err, res) { if(err) console.log(err); else { user_ids.splice( user_ids.indexOf(socket.user_id), 1 ); delete users_login_list[socket.user_id]; ifUserOnline(socket.user_id); } }); }, 2000); }); /*---------------/LOGIN USER, ADD BTNONLINE, DISCONNECT USER, DELETE BTNONLINE-----------*/ /*-----START CHAT-----*/ socket.on('startchat', function (id_author) { //создаем чат с пользователем, добавялем его в список пользователей connection.query('insert ignore into users_list_for_chat(id_user, id_user_in_list) values(?, ?)',[socket.user_id, id_author], function(err, res){ if(err) console.log(err); else { getUserslist({show_status: 1}); } }); }); socket.on('send', function (data) {//принимаем сообщение от клиента чтоб записать его в базу и вывести получателю //var msg = escape(data.msg); /*if (io.sockets.connected[users_login_list[data.usr]]!==undefined) { console.log(arrUserslist[data.usr]); //if(arrUserslist[socket.user_id]) }*/ connection.query('insert into message_in_the_chat(from_user_id, to_user_id, message, write_data) values(?, ?, ?, NOW())',[socket.user_id, data.usr, data.msg], function(err, res){ if(err) console.log(err); else { connection.query('insert into users_list_for_chat(id_user, id_user_in_list) values(?, ?)', [data.usr, socket.user_id], function(err, res){ if (err) console.log('User exist!'); else getUserslist({show_status: 1}); //console.log(io.sockets.connected[users_login_list[data.usr]]); if (io.sockets.connected[users_login_list[data.usr]]!==undefined) { io.sockets.connected[users_login_list[data.usr]].emit('sendmsg', {msg:data.msg, usr:socket.user_id}); } }); } }); }); socket.on('getUsersList', function(data){ getUserslist({show_status: data.show_status}); }); socket.on('getHistoryDialog', function(data) { //получаем историю сообщений getHistoryDialog(data); updateReadStatus(data); }); socket.on('updateReadStatus', function(data){ // обновляем статус сообщения на прочитано! updateReadStatus(data); }); socket.on('getNewMsgs', function(data) { connection.query('SELECT COUNT(message) as num from message_in_the_chat WHERE message_in_the_chat.from_user_id = ? AND message_in_the_chat.to_user_id = ? AND message_in_the_chat.read_status = 0', [data.usr_to, socket.user_id], function (err, res) { if(err) console.log(err); else { socket.emit('setNewMsgs', {num: res[0].num, usr: data.usr_to}); } }); }); socket.on('hideUserFromUserlist', function (data) { updateUserList(data); }); socket.on('dltUserFromUserlist', function (data) { //удаляем пользователя из списка контактов connection.query('DELETE FROM users_list_for_chat WHERE users_list_for_chat.id_user = ? AND users_list_for_chat.id_user_in_list = ?', [socket.user_id, data.usr_to], function (err, res) { if(err) console.log(err); else getUserslist({show_status: 1}); }); }); /*-----START CHAT-----*/ function getUserslist(data) { //функция для получения списка собеседников if (data.show_status === 'All') var show_status = ''; if (data.show_status == 1) var show_status = ' AND users_list_for_chat.show_status = 1'; if (data.show_status == 0) var show_status = ' AND users_list_for_chat.show_status = 0'; connection.query('select users.id, users.onlineSatus, users.login, user_date.name, user_date.lastname, user_date.company_name, user_date.company_link, user_date.user_img, (SELECT COUNT(message) from message_in_the_chat WHERE message_in_the_chat.to_user_id = ? AND message_in_the_chat.from_user_id = users_list_for_chat.id_user_in_list AND users_list_for_chat.id_user = ? AND message_in_the_chat.read_status = 0) as numNewMsg from users_list_for_chat LEFT JOIN users ON users.id = users_list_for_chat.id_user_in_list LEFT JOIN user_date ON users.id = user_date.user_id WHERE users_list_for_chat.id_user = ?'+show_status, [socket.user_id, socket.user_id, socket.user_id], function (err, res) { if(err) console.log(err); else { arrUserslist[socket.user_id] = res; socket.emit('createUsersList', res); } }); } function updateReadStatus(data) { //обновление статуса сообщения о прочтении на прочитано (1) connection.query('UPDATE message_in_the_chat SET read_status = 1 WHERE message_in_the_chat.from_user_id = ? AND message_in_the_chat.to_user_id =?', [data.usr_to, socket.user_id], function (err, res) { if(err) console.log(err); }); } function getHistoryDialog(data) {//получаем историю сообщений, последние 25 сообщений connection.query('select users.login, user_date.name, user_date.lastname, user_date.company_name, user_date.company_link, user_date.user_img, message_in_the_chat.id, message_in_the_chat.from_user_id, message_in_the_chat.to_user_id, message_in_the_chat.message, message_in_the_chat.read_status, DATE_FORMAT(message_in_the_chat.write_data, "%d.%m.%Y %H:%i") as msg_data from message_in_the_chat LEFT JOIN users ON users.id = message_in_the_chat.from_user_id LEFT JOIN user_date ON users.id = user_date.user_id WHERE (message_in_the_chat.from_user_id = ? AND message_in_the_chat.to_user_id =?) OR (message_in_the_chat.to_user_id = ? AND message_in_the_chat.from_user_id =?) ORDER BY write_data LIMIT 25', [socket.user_id, data.usr_to, socket.user_id, data.usr_to], function (err, res) { if(err) console.log(err); else { socket.emit('addDialogHistory', {arr:res, usr:data.usr_to}); } }); } function updateUserList(data) { //меняем статус пользователя на скрытый в списке пользователей connection.query('UPDATE users_list_for_chat SET show_status = 0 WHERE users_list_for_chat.id_user = ? AND users_list_for_chat.id_user_in_list =?', [socket.user_id, data.usr_to], function (err, res) { if(err) console.log(err); else getUserslist({show_status: 1}); }); } function ifUserOnline(id_author) { //функция проверки пользователя на присутствие на сайте connection.query('select id, login from users where onlineSatus = ? and id = ?', [1, id_author], function (err, res) { if(err) console.log(err); else { if (res.length !== 0) { io.emit('createBtnChat', {id: res[0].id, login: res[0].login}); } else { io.emit('deleteBtnChat', id_author); } } }); } });
08946c76028c488f9e1ac8fd25b197d05dddb2d7
[ "JavaScript" ]
1
JavaScript
yasacher/messendger
b968008a30a0c583d112be3a54efe5e7051cfe25
c2aca7f0caa71aae183fe57e6e0f47c25988c01a
refs/heads/master
<file_sep>人类不快乐的唯一原因是他不知道如何安静地呆在自己的房间里。 周伯通被黄老邪困在桃花岛,悟出了左右手互博。 孤僻的我写了这个HTML小程序,简单来说,用于自己和自己聊天。 并给程序起名为:没有人。 因为没有人会分享你的快乐啊,没有人能分担你的悲伤啊。没有人能永远陪着你啊。 除俗话说吾日三省吾身,这个小程序可以帮你把你和自己的对话显示在屏幕上。 每天和自己谈谈心,可以更好的认识、反省自己。^_^ PS:暂时只支持PC端布局,且不支持IE。<file_sep>var divId = 1; var sendArr = new Array(); var receivArr = new Array(); var tempArr = new Array(); window.onload = function () { var browser = navigator.appName if (browser == "Microsoft Internet Explorer") { alert("您的浏览器内核版本过低不能正常访问本站,请下载最新主流内核版本浏览器"); window.location.href = "http://www.firefox.com.cn/download/"; } } /*监测键盘录入*/ document.onkeydown = KeyPress; function KeyPress() { var key; key = KeyPress.arguments[0].keyCode; var oEvent = window.event; if(key==13){ input(); } if((oEvent.ctrlKey)&&(key==81)){ change(); } } function change() { /*两个数组的值进行相互替换*/ tempArr = []; tempArr = receivArr.concat(); receivArr = []; receivArr = sendArr.concat(); sendArr = []; sendArr = tempArr.concat(); /*替换样式*/ for (var i = 0; i < sendArr.length; i++) { document.getElementById(sendArr[i]).className = "sender"; document.getElementById('triangle' + sendArr[i]).className = "left_triangle"; document.getElementById("pic" + sendArr[i]).src = "chat/sender.png"; } for (var i = 0; i < receivArr.length; i++) { document.getElementById(receivArr[i]).className = "receiver"; document.getElementById('triangle' + receivArr[i]).className = "right_triangle"; document.getElementById("pic" + receivArr[i]).src = "chat/receiver.png"; } } function input() { var text = document.getElementById('text').value; if (text.length > '0') { /*控制页面中只显示15个消息气泡*/ if (divId > 15) { var hideId = divId - 15; /*隐藏当前第一个气泡*/ document.getElementById(hideId).className = "hide"; /*receive数组出队*/ receivArr.shift(); } /*添加一个外包元素sender*/ var message = document.getElementById('message'); var div1 = document.createElement("div"); div1.className = "receiver"; div1.setAttribute("id", divId); message.appendChild(div1); /*获取刚添加的元素为父节点,向其中添加imgDiv*/ var sender = document.getElementById(divId); var div2 = document.createElement("div"); div2.setAttribute("id", "img" + divId); sender.appendChild(div2); /*继续添向sender里添加textDiv*/ var div3 = document.createElement("div"); div3.setAttribute("id", "text" + divId); sender.appendChild(div3); /*向imgDiv里添加头像图片*/ var imgDiv = document.getElementById("img" + divId); var img = document.createElement("img"); img.setAttribute("id", "pic" + divId); img.src = "chat/receiver.png"; imgDiv.appendChild(img); /*向textDiv里添加文本消息和消息箭头 */ var textDiv = document.getElementById('text' + divId); var div4 = document.createElement("div"); div4.setAttribute("id", "triangle" + divId); div4.className = "right_triangle"; textDiv.appendChild(div4); var span = document.createElement("span"); span.innerHTML = text; textDiv.appendChild(span); /*内容添加完成,清空文本框内容,divId添加到receive数组中,并自加1*/ document.getElementById('text').value = ""; receivArr.push(divId); divId++; /*将div滚动条移动到div底部*/ document.getElementById('message').scrollTop = document.getElementById('message').scrollHeight; } else { return; } } /*文本框获得焦点时的函数*/ function textOnfocus() { document.getElementById("state").innerHTML = "没有人正在输入...."; } /*文本框失去焦点时的函数*/ function textOnblur() { document.getElementById("state").innerHTML = "没有人正在与你聊天"; }
050878470083a806ccb6309fc38532370091043f
[ "JavaScript", "Text" ]
2
Text
jaycial/chat-whit-me
58d56d0c4cdd61d008ca8c01c48e796e17df98d3
9ed1f9788aa7110cfe4f13a44864156dac2c4c61
refs/heads/master
<file_sep>package com.somitsolutions.java.training.classlevellockingwithstaticnestedclass; public class ExampleClass { public ExampleClass(){ } public static InnerNestedClass objInnerNestedClass = new InnerNestedClass(); //This is an example of Class level locking. As the class has a static //object of static nested class InnerNestedClass, it does not matter //how many objects of ExampleClass are being created... Only one object //can call the synchronized method testMethod(). If more than one objects //of ExampleClass call testMethod(), they will wait till the //current object finishes its work with testMethod(). This is what //exactly happens in Android Asynctask.java. There the Asynctask //class has a static object of the static nested class SerialExecutor. //And in the SerialExecutor class we have a synchronized method called //execute. Hence it does not matter how many objects of an Asynctask derived //class we create, if we call the execute function //on these objects, the execute function will be executed one after //the other serially... // static class InnerNestedClass{ public synchronized void testMethod(){ try { for (int i = 0; i<5; i++){ System.out.println ("The testMethod for " + Thread.currentThread().getName() + " Object"); Thread.sleep(2000); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
aa1710d7cce1447acf71a2ce5e4849b5f103d6c4
[ "Java" ]
1
Java
som-itsolutions/ClassLevelLocking
68f83a91cf55f4024f204f0a1a21b7a0390f1f54
b56e8eed1c8c08c9bcd1c97e15b2ce49e602b30b
refs/heads/master
<repo_name>Achiratch/Schedulalization<file_sep>/link.js function relocate_profile() { location.href = "profile.html"; } function relocate_login() { location.href = "login.html"; } function relocate_register() { location.href = "register.html"; } function relocate_AddSchedule() { location.href = "AddCourse.html"; }
e9fcc9a55e58d8b0147f081a61c4fe6c597b9a79
[ "JavaScript" ]
1
JavaScript
Achiratch/Schedulalization
557473b78d7725b2e98d0d78fc1c4ceb52de3545
82f2de0e4ade709de90861474308a04a4ce6fde1
refs/heads/master
<file_sep>import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { Route } from '../routes/entities/route.entity'; import { RouteAction } from './entities/route-action.entity'; import { RouteActionController } from './route-action.controller'; import { RouteActionService } from './route-action.service'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([RouteAction], DBNameConnection)], controllers: [RouteActionController], providers: [RouteActionService], exports: [RouteActionService], }) export class RouteActionModule {} <file_sep>import { LocationEntity } from './location.entity'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; export declare class LocationService extends TypeOrmCrudService<LocationEntity> { constructor(repo: any); findAll(): Promise<LocationEntity[]>; } <file_sep>import { JwtModuleOptions } from '@nestjs/jwt'; import { IAuthModuleOptions } from '@nestjs/passport'; declare const _default: (() => { port: number; jwt: JwtModuleOptions; passport: IAuthModuleOptions<any>; }) & import("@nestjs/config").ConfigFactoryKeyHost<{ port: number; jwt: JwtModuleOptions; passport: IAuthModuleOptions<any>; }>; export default _default; <file_sep>export class AcTokenDto { readonly user_id: number; readonly name: string; readonly token: string; readonly revoked: boolean; readonly createdAt: Date; readonly updatedAt: Date; readonly expiresAt: string; } <file_sep>export declare class TypelectionService { } <file_sep>import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn, ManyToOne, OneToMany } from 'typeorm'; @Entity('Election') export class ElectionEntity { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() Date: Date; @Column() active: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; } <file_sep>import { Role } from '../entities/role.entity'; const routes: Role[] = [ { id: 1, isActive: true, name: 'Admin', permissions: [], }, ] as Role[]; export default routes; <file_sep>import * as session from 'express-session'; import { INestApplication, Module } from '@nestjs/common'; import { JwtStrategy, LocalStrategy } from './strategies'; import { AuthController } from './auth.controller'; import { AuthService } from './auth.service'; import { JwtConfigService } from './jwt-config.service'; import { JwtModule } from '@nestjs/jwt'; import { PassportModule } from '@nestjs/passport'; import { RolesModule } from '../roles/roles.module'; import { UserModule } from '../user/user.module'; @Module({ imports: [ UserModule, PassportModule.register({ defaultStrategy: 'jwt', property: 'user', session: false, }), JwtModule.registerAsync({ useClass: JwtConfigService, }), RolesModule, ], providers: [AuthService, LocalStrategy, JwtStrategy], exports: [PassportModule, LocalStrategy, JwtStrategy, AuthService], controllers: [AuthController], }) export class AuthModule { constructor() {} public initialize(app: INestApplication) { app.use( session({ secret: process.env.API_SECRET, resave: false, cookie: { httpOnly: true, secure: true, maxAge: 1000 * 60 * 60 * 24 * 7, }, saveUninitialized: false, }), ); } } <file_sep>import { JwtModuleOptions, JwtOptionsFactory } from '@nestjs/jwt'; export declare class JwtConfigService implements JwtOptionsFactory { constructor(); createJwtOptions(): JwtModuleOptions; } <file_sep>export declare class RouteActionModule { } <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Route } from './entities/route.entity'; import { Repository } from 'typeorm'; export declare class RoutesService extends TypeOrmCrudService<Route> { readonly repo: Repository<Route>; constructor(repo: Repository<Route>); getRoots(): Promise<Route[]>; } <file_sep>import { Strategy } from 'passport-local'; import { AuthService } from '../auth.service'; export declare class RegisterStrategy extends Strategy { private readonly authService; name: string; constructor(authService: AuthService); } <file_sep>import { Column, Entity, OneToMany, PrimaryGeneratedColumn, Tree } from 'typeorm'; import { Permission } from '../../permissions/entities/permission.entity'; import { UserEntity } from '../../user/user.entity'; @Entity() export class Role { @PrimaryGeneratedColumn({ type: 'int', }) id: number; @Column('boolean', { nullable: false, }) isActive: boolean; @Column('varchar', { nullable: false, length: 60, }) name: string; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) createdAt: Date; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', }) updatedAt: Date; @OneToMany(() => Permission, (permission) => permission.role) permissions: Permission[]; @OneToMany(() => UserEntity, (user) => user.role ) users: UserEntity[]; } <file_sep>import { RouteAction } from '../entities/route-action.entity'; import { ActionsEnum } from '../../actions/seeds/actions.catalogue'; import { Route } from '../../routes/entities/route.entity'; import { Action } from '../../actions/entities/action.entity'; const routesActions: RouteAction[] = [ { id: 1, route: { id: 12 }, action: { id: ActionsEnum.DELETE } }, ] as unknown as RouteAction[]; export default routesActions; <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Action } from './entities/action.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class ActionsService extends TypeOrmCrudService<Action> { constructor( @InjectRepository(Action, DBNameConnection) readonly repo: Repository<Action>, ) { super(repo); } } <file_sep>import { CrudController } from '@nestjsx/crud'; import { Route } from './entities/route.entity'; import { RoutesService } from './routes.service'; export declare class RoutesController implements CrudController<Route> { readonly service: RoutesService; constructor(service: RoutesService); get base(): CrudController<Route>; getRoots(): Promise<Route[]>; } <file_sep>import { Module } from '@nestjs/common'; import { TypelectionController } from './typelection.controller'; import { TypelectionService } from './typelection.service'; @Module({ providers: [TypelectionService], controllers: [TypelectionController], }) export class TypelectionModule {} <file_sep>import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { SectionController } from './section.controller'; import { SectionEntity } from './section.entity'; import { SectionService } from './section.service'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([SectionEntity], DBNameConnection)], providers: [SectionService], controllers: [SectionController], exports: [SectionService], }) export class SectionModule {} <file_sep>import { INestApplication } from '@nestjs/common'; export declare class AuthModule { constructor(); initialize(app: INestApplication): void; } <file_sep>import { CountryController } from './country.controller'; import { CountryEntity } from './country.entity'; import { CountryService } from './country.service'; import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([CountryEntity], DBNameConnection)], providers: [CountryService], controllers: [CountryController], }) export class CountryModule {} <file_sep>import { StateEntity } from './state.entity'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; export declare class StateService extends TypeOrmCrudService<StateEntity> { constructor(repo: any); findAll(): Promise<StateEntity[]>; } <file_sep>export declare class AccesstokensModule { } <file_sep>import { RouteAction } from '../../route-action/entities/route-action.entity'; import { Permission } from '../../permissions/entities/permission.entity'; export declare class Action { id: number; name: string; createdAt: Date; updatedAt: Date; routeActions: RouteAction[]; permission: Permission[]; } <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Repository } from 'typeorm'; import { UpdatePasswordDto } from './dto/UpdatePassword.dto'; import { UserEntity } from './user.entity'; export declare class UserService extends TypeOrmCrudService<UserEntity> { readonly repo: Repository<UserEntity>; constructor(repo: Repository<UserEntity>); create(createUserDto: Partial<UserEntity>): Promise<UserEntity>; changePassword(createUserDto: UpdatePasswordDto): Promise<UserEntity>; save(user: UserEntity): Promise<UserEntity>; } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Controller('accesstokens') export class AccesstokensController {} <file_sep>import { Column, Entity, ManyToMany, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; import { Route } from '../../routes/entities/route.entity'; import { RouteAction } from '../../route-action/entities/route-action.entity'; import { Permission } from '../../permissions/entities/permission.entity'; @Entity() export class Action { @PrimaryGeneratedColumn({ type: 'int', }) id: number; @Column('varchar', { nullable: false, length: 60, }) name: string; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) createdAt: Date; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', }) updatedAt: Date; @OneToMany(type => RouteAction, routeAction => routeAction.action) routeActions: RouteAction[]; @ManyToMany(() => Permission, (permission) => permission.actions, { cascade: ['insert', 'update'], }) permission: Permission[]; } <file_sep>import { Action } from '../entities/action.entity'; declare const actions: Array<Partial<Action>>; export declare enum ActionsEnum { CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4 } export default actions; <file_sep>import { Connection, DataSource, QueryRunner } from 'typeorm'; import { Factory, Seeder, times } from 'typeorm-seedling'; import { Permission } from '../entities/permission.entity'; import PermissionCatalog from './permissions.catalogue'; export default class PermissionInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { await connection.connection .createQueryBuilder() .insert() .into(Permission) .values(PermissionCatalog) .execute(); } } <file_sep>import * as passport from 'passport'; import { Injectable, CanActivate, ExecutionContext, } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class LocalAuthGuard extends AuthGuard('local') {} <file_sep>import { SectionService } from './section.service'; import { SectionEntity } from './section.entity'; import { CrudController } from '@nestjsx/crud'; export declare class SectionController implements CrudController<SectionEntity> { service: SectionService; constructor(service: SectionService); } <file_sep>export declare class VoteService { } <file_sep>import { Injectable } from '@nestjs/common'; @Injectable() export class TypelectionService {} <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { SectionEntity } from './section.entity'; export declare class SectionService extends TypeOrmCrudService<SectionEntity> { constructor(repo: any); } <file_sep>export declare class ElectionEntity { id: number; name: string; Date: Date; active: Date; createdAt: Date; updatedAt: Date; } <file_sep>import { CrudController } from '@nestjsx/crud'; import { Permission } from './entities/permission.entity'; import { PermissionsService } from './permissions.service'; import { PermissionDto } from './DTO/permission.dto'; export declare class PermissionsController implements CrudController<Permission> { readonly service: PermissionsService; constructor(service: PermissionsService); get base(): CrudController<Permission>; getRoots(): Promise<Permission[]>; assingPermission(assignper: PermissionDto): Promise<import("typeorm").DeleteResult | Permission>; getFlatPermission(idrol: any): Promise<number[]>; getTreePermission(idrol: number): Promise<import("../routes/entities/route.entity").Route[]>; } <file_sep>import { Module } from '@nestjs/common'; import { DatabaseModule } from './database/database.module'; import { ConfigModule } from './config/config.module'; const CORE_MODULES = [ConfigModule, DatabaseModule]; @Module({ imports: CORE_MODULES, exports: CORE_MODULES, }) export class CoreModule {} <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { LocationService } from './location.service'; import { Crud, CrudController } from '@nestjsx/crud'; import { LocationEntity } from './location.entity'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: LocationEntity, }, query: { join: { state: {}, muncipality: {}, sections: {}, people: {}, }, }, }) @Controller('municipality/location') export class LocationController implements CrudController<LocationEntity> { constructor(public service: LocationService) { } } <file_sep>import { ConnectionOptions } from 'typeorm'; // Modules import { TypeOrmModule } from '@nestjs/typeorm'; import { registerAs } from '@nestjs/config'; export const DBNameConnection = 'ine'; function typeormModuleOptions(): ConnectionOptions { return { type: 'mysql', name: DBNameConnection, host: '192.168.3.11', port: (process.env.DB_PORT as unknown) as number, username: process.env.DB_USERNAME, password: <PASSWORD>, database: process.env.DB_DBNAME, seeds: [__dirname + '/../**/*.seed{.ts,.js}'], entities: [__dirname + '/../**/*.entity{.ts,.js}'], synchronize: true, migrations: [__dirname + '/../migrations/**/*{.ts,.js}'], cli: { migrationsDir: 'src/migrations', }, } as ConnectionOptions; } export default registerAs('database', () => ({ config: typeormModuleOptions(), })); <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { JwtGuard } from '../auth/guards/jwt.guard'; import { Crud, CrudController } from '@nestjsx/crud'; import { RouteAction } from './entities/route-action.entity'; import { RouteActionService } from './route-action.service'; @UseGuards(JwtGuard) @Crud({ model: { type: RouteAction, }, query: { join: { actions: {}, }, }, }) @Controller() export class RouteActionController implements CrudController<RouteAction> { constructor( readonly service: RouteActionService, ) { } get base(): CrudController<RouteAction> { return this; } } <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Permission } from './entities/permission.entity'; import { Repository } from 'typeorm'; export declare class PermissionsService extends TypeOrmCrudService<Permission> { readonly repo: Repository<Permission>; constructor(repo: Repository<Permission>); getRoots(): Promise<Permission[]>; getPermissionTree(idrol: any): Promise<void>; } <file_sep>import { JwtModuleOptions, JwtOptionsFactory } from '@nestjs/jwt'; import { Injectable } from '@nestjs/common'; @Injectable() export class JwtConfigService implements JwtOptionsFactory { constructor() {} createJwtOptions(): JwtModuleOptions { return { secret: process.env.API_SECRET, signOptions: { expiresIn: '7d' }, }; } } <file_sep>import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { CountryEntity } from './country.entity'; import { Repository } from 'typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class CountryService { constructor( @InjectRepository(CountryEntity, DBNameConnection) private readonly countryRepository: Repository<CountryEntity>, ) {} async findAll(): Promise<CountryEntity[]> { return await this.countryRepository.find({ where: { states: { id: 2, }, }, relations: [ 'states', 'states.municipalitys', 'states.municipalitys.locations', ], }); } } <file_sep>import { RegisterStrategy } from './register.strategy'; import { LocalStrategy } from './local.strategy'; import { JwtStrategy } from './jwt.strategy'; export { RegisterStrategy, LocalStrategy, JwtStrategy, }; <file_sep>import { Permission } from '../../permissions/entities/permission.entity'; import { UserEntity } from '../../user/user.entity'; export declare class Role { id: number; isActive: boolean; name: string; createdAt: Date; updatedAt: Date; permissions: Permission[]; users: UserEntity[]; } <file_sep>import * as Excel from 'exceljs'; import { CustomerEntity } from '../customer.entity'; export declare class ReporteCustomer { generate(data: CustomerEntity[]): Promise<string>; addPerson(paymentsSheet: Excel.Worksheet, data: CustomerEntity[]): void; private typePersona; } <file_sep>import { CrudController } from '@nestjsx/crud'; import { CustomerEntity } from './customer.entity'; import { CustomerService } from './customer.service'; import { Response } from 'express'; export declare class CustomerController implements CrudController<CustomerEntity> { service: CustomerService; constructor(service: CustomerService); dasbboardCount(): Promise<{ activista: number; promovido: number; lider: number; }>; dasbboardCountType(): Promise<any[]>; report(req: any, res: Response, query: { stateId: number; municipalityId: number; zonaId: number; seccionId: number; typePerson: number; }): Promise<void>; } <file_sep>import { Role } from '../../roles/entities/role.entity'; import { Route } from '../../routes/entities/route.entity'; import { Action } from '../../actions/entities/action.entity'; export declare class Permission { id: number; routeId: number; createdAt: Date; updatedAt: Date; role: Role; route: Route; actions: Action[]; } <file_sep>import { Column, Entity, ManyToOne, OneToOne, PrimaryGeneratedColumn, } from 'typeorm'; import { SectionEntity } from '../section/section.entity'; import { LocationEntity } from '../location/location.entity'; import { UserEntity } from '../user/user.entity'; import { MunicipalityEntity } from '../municipality/municipality.entity'; import { StateEntity } from '../state/state.entity'; export enum TypeOfPeople { Lider = 1, Promovido = 2, Activista = 3, } @Entity('customer') export class CustomerEntity { @PrimaryGeneratedColumn({ type: 'int' }) id: number; @Column('varchar', { nullable: true, }) name: string; @Column('varchar', { nullable: true, length: 60, }) lastNameFather: string | null; @Column('varchar', { nullable: true, length: 60, }) lastNameMother: string | null; @Column('varchar', { nullable: true, length: 18, unique: true }) clave: string | null; @Column('varchar', { nullable: true, }) phone: string | null; @Column('varchar', { nullable: true, }) direccion: string | null; @Column('int', { nullable: true, }) peopleId: number | null; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) createdAt: Date; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', }) updatedAt: Date; @Column({ type: 'simple-enum', nullable: true, enum: TypeOfPeople, }) typeOfPeople: TypeOfPeople; @ManyToOne( type => StateEntity, state => state.people, { cascade: ['insert'], }, ) state: StateEntity; @ManyToOne( type => MunicipalityEntity, mun => mun.people, { cascade: ['insert'], }, ) municipality: MunicipalityEntity; @ManyToOne( type => LocationEntity, location => location.people, { cascade: ['insert'], }, ) zona: LocationEntity; @ManyToOne( type => SectionEntity, sec => sec.people, { cascade: ['insert'], }, ) section: SectionEntity; @OneToOne( type => UserEntity, user => user.people, { cascade: ['insert'], }, ) user: UserEntity; @Column('varchar', { nullable: true, length: 60, }) facebook: string | null; @Column('varchar', { nullable: true, length: 60, }) instagram: string | null; @Column('varchar', { nullable: true, length: 60, }) twitter: string | null; @Column('varchar', { nullable: true, length: 60, }) email: string | null; @Column() voto: boolean; @Column({ nullable: false, length: 250 }) searchName: string } <file_sep>// You can load you .env file here synchronously using dotenv package (not installed here), import * as dotenv from 'dotenv'; import * as fs from 'fs'; import { DataSource } from 'typeorm-seedling'; const environment = process.env.NODE_ENV || 'development'; const processEnv: any = dotenv.parse( fs.readFileSync(`environment/.env.${environment}`), ); // You can also make a singleton service that load and expose the .env file content. // ... // Check typeORM documentation for more information. console.log(`Migración corriendo --> en entorno ${environment}`); console.log( `Migración corriendo --> en la base de datos ${processEnv.DB_DBNAME}`, ); const config = new DataSource({ type: 'mysql', name: 'ine', migrationsTableName: 'migrations_typeorm', host: processEnv.DB_HOST, port: processEnv.DB_PORT, username: processEnv.DB_USERNAME, password: <PASSWORD>, database: processEnv.DB_DBNAME, entities: [__dirname + '/**/*.entity{.ts,.js}'], // @ts-ignore seeds: [__dirname + '/**/*.seed{.ts,.js}'], factories: [__dirname + '/**/*.factory{.ts,.js}'], // We are using migrations, synchronize should be set to false. synchronize: false, // Run migrations automatically, // you can disable this if you prefer running migration manually. migrationsRun: true, logging: true, logger: 'file', // Allow both start:prod and start:dev to use migrations // __dirname is either dist or src folder, meaning either // the compiled js in prod or the ts in dev. migrations: [__dirname + '/migrations/**/*{.ts,.js}'], cli: { // Location of migration should be inside src folder // to be compiled into dist/ folder. migrationsDir: 'src/migrations', }, }); export = config; <file_sep>import { Body, Controller, Get, Param, Post, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { Permission } from './entities/permission.entity'; import { PermissionsService } from './permissions.service'; import { PermissionDto } from './DTO/permission.dto'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: Permission, }, query: { join: { role: {}, route: {}, actions: {} }, }, }) @Controller('system/permissions') export class PermissionsController implements CrudController<Permission> { constructor( readonly service: PermissionsService, ) { } get base(): CrudController<Permission> { return this; } @Get('roots') async getRoots() { return await this.service.getRoots(); } @Post('assignpermissions') async assingPermission(@Body() assignper: PermissionDto) { // const permission = await this.service.repo.findOne({ where: { roleId: assignper.roleId, routeId: assignper.routeId }}) const permission = await this.service.repo.findOne({ where: { role: { id: assignper.roleId, }, route: { id: assignper.routeId, }, }, }); if (permission) { return await this.service.repo.delete(permission.id); } else { const newperrmision = this.service.repo.create({ role: { id: assignper.roleId, }, route: { id: assignper.routeId, }, }); return await this.service.repo.save(newperrmision); } // return assignper; // return await this.service.getRoots(); } @Get('assignpermissions/:id') async getFlatPermission(@Param('id') idrol: any) { const permissions = await this.service.repo.find({ where: { role: { id: idrol, }, }, select: ['routeId'], }); return permissions.map((data) => { return data.routeId; }); } @Get('getpermission/:id') async getTreePermission(@Param('id') idrol: number) { /*await this.service.repo.find({ where: { role: { id: idrol, }, route: { isActive: 0, }, }, relations: ['route', 'role'], });*/ const permissions = await this.service.repo.createQueryBuilder('permission') .leftJoinAndSelect('permission.route', 'route', 'permission.route = route.id') .leftJoinAndSelect('permission.role', 'role', 'permission.role = role.id') .where('permission.role = :id', { id: idrol }) .andWhere('role.isActive = :active', { active: true }) .andWhere('route.isActive = :active', { active: 1 }) .getMany() ; return permissions.map((data) => { return data.route; }); } } <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Action } from './entities/action.entity'; import { Repository } from 'typeorm'; export declare class ActionsService extends TypeOrmCrudService<Action> { readonly repo: Repository<Action>; constructor(repo: Repository<Action>); } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Controller('election') export class ElectionController {} <file_sep>import { Controller, Get, Query, Req, Res, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { CustomerEntity, TypeOfPeople } from './customer.entity'; import { CustomerService } from './customer.service'; import { Response } from 'express'; import { ReporteCustomer } from './reporte/reporteCustomer'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: CustomerEntity, }, query: { join: { state: {}, municipality: {}, zona: {}, section: {}, user: {}, }, }, }) @Controller('elections/customer') export class CustomerController implements CrudController<CustomerEntity> { constructor(public service: CustomerService) { } @Get('dashboard/count') async dasbboardCount() { const respuesta = { activista: 0, promovido: 0, lider: 0, }; respuesta.lider = await this.service.count({ where: { typeOfPeople: TypeOfPeople.Lider } }); respuesta.activista = await this.service.count({ where: { typeOfPeople: TypeOfPeople.Activista } }); respuesta.promovido = await this.service.count({ where: { typeOfPeople: TypeOfPeople.Promovido } }); return respuesta; } @Get('dashboard/count-type') async dasbboardCountType() { const result = []; result.push({ label: 'Lider', quantity: await this.service.count({ where: { typeOfPeople: TypeOfPeople.Lider } }), }); result.push({ label: 'activista', quantity: await this.service.count({ where: { typeOfPeople: TypeOfPeople.Activista } }), }); result.push({ label: 'Promovido', quantity: await this.service.count({ where: { typeOfPeople: TypeOfPeople.Promovido } }), }); return result; } @Get('report') async report(@Req() req, @Res() res: Response, @Query() query: { stateId: number, municipalityId: number, zonaId: number, seccionId: number, typePerson: number, }) { const customer = this.service.repo.createQueryBuilder('customer'); customer.leftJoinAndSelect('customer.state', 'state'); customer.leftJoinAndSelect('customer.municipality', 'municipality'); customer.leftJoinAndSelect('customer.zona', 'zona'); customer.leftJoinAndSelect('customer.section', 'section'); if (query.stateId && query.stateId !== 0 && query.stateId.toString() !== '0') { customer.where('state.id = :id', { id: query.stateId, }); } if (query.municipalityId && query.municipalityId !== 0 && query.municipalityId.toString() !== '0') { customer.where('municipality.id = :id', { id: query.municipalityId, }); } if (query.zonaId && query.zonaId !== 0 && query.zonaId.toString() !== '0') { customer.where('zona.id = :id', { id: query.zonaId, }); } if (query.seccionId && query.seccionId !== 0 && query.seccionId.toString() !== '0') { customer.where('section.id = :id', { id: query.seccionId, }); } if (query.typePerson && query.typePerson !== 0 && query.typePerson.toString() !== '0') { customer.where('typeOfPeople = :type', { type: query.typePerson, }); } const reporte = await customer.getMany(); res.send({ src: await new ReporteCustomer().generate(reporte) }); } } <file_sep>import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn, ManyToOne, BeforeInsert, BeforeUpdate } from 'typeorm'; @Entity('access_tokens') export class AccessTokensEntity { @PrimaryGeneratedColumn() id: number; @Column() user_id: number; @Column() name: string; @Column('text') token: string; @Column() revoked: boolean; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; @Column() expiresAt: string; } <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { hash } from 'bcrypt'; import { UpdatePasswordDto } from './dto/UpdatePassword.dto'; import { UserEntity } from './user.entity'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class UserService extends TypeOrmCrudService<UserEntity> { constructor( @InjectRepository(UserEntity, DBNameConnection) readonly repo: Repository<UserEntity>, ) { super(repo); } public async create(createUserDto: Partial<UserEntity>): Promise<UserEntity> { createUserDto.password = await hash(createUserDto.password, 8); return this.repo.create({ ...createUserDto }); } public async changePassword( createUserDto: UpdatePasswordDto, ): Promise<UserEntity> { createUserDto.password = await hash(createUserDto.password, 8); return this.repo.create({ ...createUserDto }); } public async save(user: UserEntity): Promise<UserEntity> { return this.repo.save(user); } } <file_sep>import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; import { CountryEntity } from '../country/country.entity'; import { MunicipalityEntity } from '../municipality/municipality.entity'; import { LocationEntity } from '../location/location.entity'; import { SectionEntity } from '../section/section.entity'; import { CustomerEntity } from '../customer/customer.entity'; @Entity('state') export class StateEntity { @PrimaryGeneratedColumn() id: number; @Column() abrev: string; @Column() name: string; @Column() cod_tel: string; @ManyToOne(type => CountryEntity, country => country.states, { cascade: ['insert'], }) country: CountryEntity; @OneToMany(type => MunicipalityEntity, municipality => municipality.state, { cascade: ['insert'], }) municipalitys: MunicipalityEntity[]; @OneToMany(type => LocationEntity, location => location.state, { cascade: ['insert'], }) locations: LocationEntity[]; @OneToMany(type => SectionEntity, section => section.state, { cascade: ['insert'], }) sections: SectionEntity[]; @OneToMany(type => CustomerEntity, section => section.state, { cascade: ['insert'], }) people: CustomerEntity[]; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; } <file_sep>import { Connection, DataSource, QueryRunner } from 'typeorm'; import { Factory, Seeder, times } from 'typeorm-seedling'; import { UserEntity } from '../user.entity'; import { hash } from 'bcrypt'; import users from './users.catalogue'; export default class UsersInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { const usersByCrypt = await Promise.all( users.map(async u => { return { ...u, password: await hash(u.password, 8), }; }), ); console.log(usersByCrypt); await connection.connection .createQueryBuilder() .insert() .into(UserEntity) .values(usersByCrypt) .execute(); } } <file_sep>import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { StateController } from './state.controller'; import { StateEntity } from './state.entity'; import { StateService } from './state.service'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([StateEntity], DBNameConnection)], providers: [StateService], controllers: [StateController], exports: [StateService], }) export class StateModule {} <file_sep>import * as Excel from 'exceljs'; import { CustomerEntity, TypeOfPeople } from '../customer.entity'; export class ReporteCustomer { async generate(data: CustomerEntity[]) { const workbook = new Excel.Workbook(); workbook.views = [ { x: 0, y: 0, width: 10000, height: 20000, firstSheet: 0, activeTab: 2, visibility: 'visible', }, ]; const personas = workbook.addWorksheet('Personas', { properties: { tabColor: { argb: '359c5b', }, }, }); this.addPerson(personas, data); const result = await workbook.xlsx.writeBuffer({ filename: (+new Date()).toString() + '.xlsx', }, ); const buffer = Buffer.from(result); const b64Encoding = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'; return b64Encoding + buffer.toString('base64'); } addPerson(paymentsSheet: Excel.Worksheet, data: CustomerEntity[]) { const peopledata = []; data.forEach((peop) => { const transforms = []; transforms.push(peop.name + ' ' + peop.lastNameFather + '' + peop.lastNameMother); transforms.push(peop.clave); transforms.push(peop.phone); transforms.push(peop.direccion); transforms.push(this.typePersona(peop.typeOfPeople)); transforms.push(peop.state.name); transforms.push(peop.municipality.name); transforms.push(peop.zona.name); transforms.push(peop.section.name); transforms.push(''); // transforms.push(peop.facebook); // transforms.push(peop.instagram); // transforms.push(peop.twitter); transforms.push(peop.email); peopledata.push(transforms); }); paymentsSheet.addTable({ name: 'personas', ref: 'F1', style: { showColumnStripes: true, }, columns: [ { name: 'Nombre' }, { name: '<NAME>' }, { name: 'Telefono' }, { name: 'Direccion' }, { name: 'Tipo' }, { name: 'Estado' }, { name: 'Municipio' }, { name: 'zona' }, { name: 'seccion' }, { name: 'Reclutador' }, // { name: 'facebook' }, // { name: 'instagram' }, // { name: 'twitter' }, { name: 'email' }, ], rows: peopledata, }); } private typePersona(type: TypeOfPeople) { let text = ''; switch (type) { case TypeOfPeople.Activista: text = 'Activistas'; break; case TypeOfPeople.Lider: text = 'Lider'; break; case TypeOfPeople.Promovido: text = 'Promovido'; break; default: text = ''; } return text; } } <file_sep>import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { AccessTokensEntity } from './accessTokens.entity'; import { Repository } from 'typeorm'; import { AcTokenDto } from './dto/AcToken.dto'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class AccesstokensService { constructor( @InjectRepository(AccessTokensEntity, DBNameConnection) private readonly acTokensRepository: Repository<AccessTokensEntity>, ) {} public async createAccesToken(createuserDTO: AcTokenDto): Promise<any> { return await this.acTokensRepository.save(createuserDTO); // const newProduct = new this.userRepository(createProductDTO); // return newProduct.save(); } } <file_sep>import { Controller, Get, Post, Req, Res, UnauthorizedException, UseGuards } from '@nestjs/common'; import { Response } from 'express'; import { RegisterGuard } from './guards/register.guard'; import { AuthGuard } from '@nestjs/passport'; import { AuthService } from './auth.service'; import { JwtGuard } from './guards/jwt.guard'; import { LocalAuthGuard } from './guards/login.guard'; // import { AuthAccessTokensService } from '../auth-access-tokens/auth-access-tokens.service'; import * as moment from 'moment'; import { RefreshGuard } from './guards/refresh.guard'; import { RolesService } from '../roles/roles.service'; import routes from '../routes/seeds/route.catalogue'; @Controller('system/auth') export class AuthController { constructor(readonly authService: AuthService, readonly roleService: RolesService, // readonly authAccessTokensService: AuthAccessTokensService ) { } @UseGuards(LocalAuthGuard) @Post('login') async login(@Req() req, @Res() res: Response) { const jwt = await this.authService.generateJWT(req.user); // tslint:disable-next-line:no-shadowed-variable const routes = await this.roleService.getPermissionRol(req.user.role.id); // await this.authAccessTokensService.saveToken({ // expiresAt: moment(jwt.decode.exp * 1000).toDate(), // name: 'token', // revoked: false, // jwt: jwt.access_token, // isActive: true, // refresh: false, // scopes: '[]', // clientId: 1, // userId: req.user.id, // }); res.status(200); res.send({ user: req.user, permission: routes.permissions, token: jwt.access_token, }); } @UseGuards(RegisterGuard) @Post('register') async register(@Req() req, @Res() res: Response) { res.status(200); res.send(req.user); } // @UseGuards(RefreshGuard) // @Post('refresh-token') // async refresToken(@Req() req, @Res() res: Response) { // const { token, sub, username } = req.user; // // const lastToken = await this.authAccessTokensService.findToken(token); // if (lastToken) { // // const jwt = await this.authService.generateJWT({ id: sub, email: username }); // lastToken.jwt = jwt.access_token; // lastToken.expiresAt = moment(jwt.decode.exp * 1000).toDate(); // lastToken.refresh = true; // this.authAccessTokensService.repo.save(lastToken); // res.status(200); // res.send({ // refresh_token: jwt.access_token, // }); // } // throw new UnauthorizedException('Not Found Token'); // } // @UseGuards(SessionGuard) @Get('logout') public logout(@Req() req, @Res() res) { res.send(req); } @UseGuards(AuthGuard('jwt')) @Post('jwt') public getJWT(@Req() req, @Res() res: Response) { res.status(201).json(req.user); } @UseGuards(JwtGuard) @Get('me') public checkMySession(@Req() req, @Res() res: Response) { res.status(201).json(req.user); } } <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Permission } from './entities/permission.entity'; import { Repository } from 'typeorm'; import { InjectRepository } from '@nestjs/typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class PermissionsService extends TypeOrmCrudService<Permission> { constructor( @InjectRepository(Permission, DBNameConnection) readonly repo: Repository<Permission>, ) { super(repo); } public getRoots() { return this.repo.manager.getTreeRepository(Permission).findTrees(); } async getPermissionTree(idrol) { // await this.repo.manager.getTreeRepository('permission').createAncestorsQueryBuilder() /*const permissions = await this.repo.manager.getTreeRepository('permission') // await this.repo.manager.getTreeRepository('permission').createAncestorsQueryBuilder() /* const permissions = await this.repo.manager.getTreeRepository('permission') .leftJoinAndSelect('permission.route', 'route', 'permission.route = route.id') .leftJoinAndSelect('permission.role', 'role', 'permission.role = role.id') .where('permission.role = :id', { id: idrol }) .andWhere('role.isActive = :active', { active: true }) .andWhere('route.isActive = :active', { active: 1 }) .getMany() ; return permissions.map((data) => { return data.route; });*/ } } <file_sep>import { CrudController } from '@nestjsx/crud'; import { StateEntity } from './state.entity'; import { StateService } from './state.service'; export declare class StateController implements CrudController<StateEntity> { service: StateService; constructor(service: StateService); findAll(): Promise<StateEntity[]>; } <file_sep>import { DataSource } from 'typeorm-seedling'; declare const config: DataSource; export = config; <file_sep>import { Test, TestingModule } from '@nestjs/testing'; import { TypelectionController } from './typelection.controller'; describe('Typelection Controller', () => { let controller: TypelectionController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [TypelectionController], }).compile(); controller = module.get<TypelectionController>(TypelectionController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); }); <file_sep>import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { MunicipalityController } from './municipality.controller'; import { MunicipalityEntity } from './municipality.entity'; import { MunicipalityService } from './municipality.service'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([MunicipalityEntity], DBNameConnection)], providers: [MunicipalityService], controllers: [MunicipalityController], exports: [MunicipalityService], }) export class MunicipalityModule {} <file_sep>import { Injectable } from '@nestjs/common'; import { MunicipalityEntity } from './municipality.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class MunicipalityService extends TypeOrmCrudService< MunicipalityEntity > { constructor(@InjectRepository(MunicipalityEntity, DBNameConnection) repo) { super(repo); } async findAll(): Promise<MunicipalityEntity[]> { return await this.repo.find({ relations: ['locations'], }); } } <file_sep>import { Body, Controller, Get, Post, Req, Res, UseGuards, } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { UserEntity } from './user.entity'; import { UserService } from './user.service'; import { Response } from 'express'; import { UpdatePasswordDto } from './dto/UpdatePassword.dto'; import { JwtGuard } from '../auth/guards/jwt.guard'; import { EntityMetadata } from 'typeorm'; import * as bcrypt from 'bcrypt'; interface DataBase { name: string; tableName: string; } @UseGuards(JwtGuard) @Crud({ model: { type: UserEntity, }, query: { exclude: ['password', 'rememberToken'], join: { role: {}, people: {}, }, }, }) @Controller('system/users') export class UserController implements CrudController<UserEntity> { constructor(readonly service: UserService) {} get base(): CrudController<UserEntity> { return this; } @Get('tables') async getTables() { const entities: DataBase[] = []; ( await (await this.service.repo.createQueryBuilder().connection) .entityMetadatas ).forEach(async (x: EntityMetadata, i) => { entities.push({ name: x.name, tableName: x.tableName, }); }); return entities; } @Post('drop-data-base') async cleanAll( @Body() userBody: { email: string; password: string }, @Req() req, @Res() res: Response, ) { try { const user: UserEntity | undefined = await this.service.repo .createQueryBuilder('users') .leftJoinAndSelect('users.role', 'role') .where('users.email = :email', { email: userBody.email }) .getOne(); if ( user && bcrypt.compareSync( userBody.password, user.password.replace('$2y$', <PASSWORD>$'), ) ) { const repository = await this.service.repo.createQueryBuilder() .connection; await repository.dropDatabase(); if (repository.isConnected) { await repository.close(); } res.status(200); res.send({ status: 200, msg: 'Base de datos eliminada', }); } else { res.status(400); res.send({ status: 400, msg: 'Datos incorrectos', }); } } catch (error) { res.status(400); res.send({ status: 400, msg: 'Datos incorrectos', }); } } @Post('store') async createNewUser( @Body() userBody: Partial<UserEntity>, @Req() req, @Res() res: Response, ) { try { const { email } = userBody; const user: UserEntity | undefined = await this.service.findOne({ where: { email }, }); if (user) { res.status(401); res.send({ msg: 'user exist' }); } else { const result = await this.service.save( await this.service.create(userBody), ); res.send(result); } } catch (e) { res.status(401); res.send(e); } } @Post('update-password') async updatePassword( @Body() userBody: UpdatePasswordDto, @Req() req, @Res() res: Response, ) { try { const { id } = userBody; const user: UserEntity | undefined = await this.service.findOne({ where: { id }, }); if (user) { const result = await this.service.save( await this.service.changePassword(userBody), ); res.send({ msg: 'password change' }); } else { res.status(401); res.send({ msg: 'user no exist' }); } } catch (e) { res.status(401); res.send(e); } } } <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Repository } from 'typeorm'; import { RouteAction } from './entities/route-action.entity'; export declare class RouteActionService extends TypeOrmCrudService<RouteAction> { readonly repo: Repository<RouteAction>; constructor(repo: Repository<RouteAction>); } <file_sep>import { Column, Entity, ManyToOne, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; import { MunicipalityEntity } from '../municipality/municipality.entity'; import { LocationEntity } from '../location/location.entity'; import { CustomerEntity } from '../customer/customer.entity'; import { StateEntity } from '../state/state.entity'; @Entity('section') export class SectionEntity { @PrimaryGeneratedColumn() id: number; @Column() name: string; @ManyToOne(type => StateEntity, state => state.sections, { cascade: ['insert'], }) state: StateEntity; @ManyToOne(type => MunicipalityEntity, mun => mun.sections, { cascade: ['insert'], }) municipality: MunicipalityEntity; @ManyToOne(type => LocationEntity, location => location.sections, { cascade: ['insert'], }) location: LocationEntity; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; @OneToMany(type => CustomerEntity, people => people.section) people: CustomerEntity[]; } <file_sep>import { CountryEntity } from '../country/country.entity'; import { MunicipalityEntity } from '../municipality/municipality.entity'; import { LocationEntity } from '../location/location.entity'; import { SectionEntity } from '../section/section.entity'; import { CustomerEntity } from '../customer/customer.entity'; export declare class StateEntity { id: number; abrev: string; name: string; cod_tel: string; country: CountryEntity; municipalitys: MunicipalityEntity[]; locations: LocationEntity[]; sections: SectionEntity[]; people: CustomerEntity[]; createdAt: Date; updatedAt: Date; } <file_sep>import { Column, Entity, JoinTable, ManyToMany, ManyToOne, PrimaryGeneratedColumn, Tree, TreeChildren, TreeParent } from 'typeorm'; import { Role } from '../../roles/entities/role.entity'; import { Route } from '../../routes/entities/route.entity'; import { Action } from '../../actions/entities/action.entity'; @Entity() export class Permission { @PrimaryGeneratedColumn({ type: 'int', }) id: number; @Column('int', { nullable: true }) routeId: number; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) createdAt: Date; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', }) updatedAt: Date; @ManyToOne(() => Role, (role) => role.permissions) role: Role; @ManyToOne(() => Route, (route) => route.permissions ) route: Route; @ManyToMany(() => Action, (action) => action.permission, { cascade: ['insert', 'update', 'remove'], }) @JoinTable() actions: Action[]; } <file_sep>import { RegisterStrategy } from './register.strategy'; import { LocalStrategy } from './local.strategy'; import { JwtStrategy } from './jwt.strategy'; export { RegisterStrategy, LocalStrategy, JwtStrategy, }; <file_sep>export declare class ElectionService { } <file_sep>export declare class TypelectionModule { } <file_sep>import { CrudController } from '@nestjsx/crud'; import { UserEntity } from './user.entity'; import { UserService } from './user.service'; import { Response } from 'express'; import { UpdatePasswordDto } from './dto/UpdatePassword.dto'; interface DataBase { name: string; tableName: string; } export declare class UserController implements CrudController<UserEntity> { readonly service: UserService; constructor(service: UserService); get base(): CrudController<UserEntity>; getTables(): Promise<DataBase[]>; cleanAll(userBody: { email: string; password: string; }, req: any, res: Response): Promise<void>; createNewUser(userBody: Partial<UserEntity>, req: any, res: Response): Promise<void>; updatePassword(userBody: UpdatePasswordDto, req: any, res: Response): Promise<void>; } export {}; <file_sep>export interface UserInterface { id: number; firstname: string; lastname: string; address: string; electorkey: string; telephone: string; email: string; password: string; updatedAt: Date; } <file_sep>import { Injectable } from '@nestjs/common'; import { StateEntity } from './state.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class StateService extends TypeOrmCrudService<StateEntity> { constructor(@InjectRepository(StateEntity, DBNameConnection) repo) { super(repo); } async findAll(): Promise<StateEntity[]> { return await this.repo.find({ relations: ['municipalitys', 'municipalitys.locations'], }); } } <file_sep>import { MunicipalityEntity } from './municipality.entity'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; export declare class MunicipalityService extends TypeOrmCrudService<MunicipalityEntity> { constructor(repo: any); findAll(): Promise<MunicipalityEntity[]>; } <file_sep>import { Connection, QueryRunner } from 'typeorm'; import { Factory, Seeder } from 'typeorm-seedling'; import { Action } from '../entities/action.entity'; import { Route } from '../../routes/entities/route.entity'; import actions from './actions.catalogue'; import routes from '../../routes/seeds/route.catalogue'; export default class ActionInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { //await connection.getRepository(Action).save(actions); await connection.connection .createQueryBuilder() .insert() .into(Action) .values(actions) .execute(); } } <file_sep>import { Column, Entity, JoinColumn, ManyToOne, OneToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Role } from '../roles/entities/role.entity'; import { LocationEntity } from '../location/location.entity'; import { CustomerEntity } from '../customer/customer.entity'; @Entity('user') export class UserEntity { @PrimaryGeneratedColumn() id: number; @Column() firstname: string; @Column() lastname: string; @Column({ unique: true, }) email: string; @Column() password: string; // @Column({ nullable: true }) // idRolId: number; @ManyToOne(() => Role, (role) => role.users, { cascade: ['insert'], }) role: Role; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; @OneToOne(type => CustomerEntity, state => state.user, { cascade: ['insert'], }) @JoinColumn() people: LocationEntity; } <file_sep>import { Connection, QueryRunner } from 'typeorm'; import { Factory, Seeder } from 'typeorm-seedling'; import { RouteAction } from '../entities/route-action.entity'; import routesActions from './route-action.catalogue'; export default class RouteActionInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { //await connection.getRepository(RouteAction).save([...routesActions]); await connection.connection .createQueryBuilder() .insert() .into(RouteAction) .values([...routesActions]) .execute(); } } <file_sep>import { AccesstokensModule } from './accesstokens/accesstokens.module'; import { ActionsModule } from './actions/actions.module'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { AuthModule } from './auth/auth.module'; import { CoreModule } from './core'; import { CountryModule } from './country/country.module'; import { CustomerModule } from './customer/customer.module'; import { ElectionModule } from './election/election.module'; import { LocationModule } from './location/location.module'; import { Module } from '@nestjs/common'; import { MunicipalityModule } from './municipality/municipality.module'; import { PermissionsModule } from './permissions/permissions.module'; import { RolesModule } from './roles/roles.module'; import { RouteActionModule } from './route-action/route-action.module'; import { RoutesModule } from './routes/routes.module'; import { SectionModule } from './section/section.module'; import { StateModule } from './state/state.module'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { TypeOrmModule } from '@nestjs/typeorm'; import { TypelectionModule } from './typelection/typelection.module'; import { UserModule } from './user/user.module'; import { VoteModule } from './vote/vote.module'; // @ts-ignore left join only // tslint:disable-next-line:only-arrow-functions TypeOrmCrudService.prototype.getJoinType = function(s: string) { // tslint:disable-next-line:no-console return 'leftJoin'; }; @Module({ imports: [ CoreModule, CountryModule, StateModule, MunicipalityModule, SectionModule, UserModule, ElectionModule, RoutesModule, PermissionsModule, RolesModule, RouteActionModule, ActionsModule, VoteModule, TypelectionModule, LocationModule, AuthModule, AccesstokensModule, CustomerModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {} <file_sep>import { ExecutionContext } from '@nestjs/common'; declare const RefreshGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>; export declare class RefreshGuard extends RefreshGuard_base { canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>; handleRequest(err: any, user: any, info: any, context: ExecutionContext, status?: any): any; } export {}; <file_sep>export declare const NODE_ENV = "NODE_ENV"; export declare const CONFIG_SERVER_PORT = "server.port"; export declare const CONFIG_SERVER_JWT = "server.jwt"; export declare const CONFIG_SERVER_JWT_SECRET = "server.jwt.secret"; export declare const CONFIG_SERVER_PASSPORT = "server.passport"; export declare const CONFIG_DB_CONFIG = "database.config"; export declare const CONFIG_REDIS_CONFIG = "redis.config"; export declare const CONFIG_MAILER_CONFIG = "mailer.config"; export declare const PATTERN_VALID_USERNAME: RegExp; export declare const PATTERN_VALID_EMAIL: RegExp; export declare const IS_PUBLIC_KEY = "isPublic"; <file_sep>import { MunicipalityEntity } from '../municipality/municipality.entity'; import { LocationEntity } from '../location/location.entity'; import { CustomerEntity } from '../customer/customer.entity'; import { StateEntity } from '../state/state.entity'; export declare class SectionEntity { id: number; name: string; state: StateEntity; municipality: MunicipalityEntity; location: LocationEntity; createdAt: Date; updatedAt: Date; people: CustomerEntity[]; } <file_sep>import { Connection, DataSource, QueryRunner } from 'typeorm'; import { Factory, Seeder, times } from 'typeorm-seedling'; import { Query } from 'typeorm/driver/Query'; import { Route } from '../entities/route.entity'; import routes from './route.catalogue'; export default class RouteInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { //await connection. (Route).save(routes); //await factory(Route)().createMany() await connection.connection .createQueryBuilder() .insert() .into(Route) .values(routes) .execute(); } } <file_sep>export declare class TypelectionController { } <file_sep>import { ExecutionContext } from '@nestjs/common'; declare const JwtGuard_base: import("@nestjs/passport").Type<import("@nestjs/passport").IAuthGuard>; export declare class JwtGuard extends JwtGuard_base { canActivate(context: ExecutionContext): boolean | Promise<boolean> | import("rxjs").Observable<boolean>; handleRequest(err: any, user: any, info: any, context: ExecutionContext, status?: any): any; } export {}; <file_sep>import { CrudController } from '@nestjsx/crud'; import { RouteAction } from './entities/route-action.entity'; import { RouteActionService } from './route-action.service'; export declare class RouteActionController implements CrudController<RouteAction> { readonly service: RouteActionService; constructor(service: RouteActionService); get base(): CrudController<RouteAction>; } <file_sep>// import { RolEntity } from '../../rol/rol.entity'; export class CreateUserDTO { readonly firstname: string; readonly lastname: string; readonly address: string; readonly electorkey: string; readonly telephone: string; readonly email: string; password: string; readonly confirm_password: string; // readonly id_rol: RolEntity; } <file_sep>/* tslint:disable:object-literal-key-quotes */ import { Controller, UseGuards } from '@nestjs/common'; import { MunicipalityService } from './municipality.service'; import { Crud, CrudController } from '@nestjsx/crud'; import { MunicipalityEntity } from './municipality.entity'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: MunicipalityEntity, }, query: { join: { state: {}, locations: {}, 'locations.muncipality': {}, 'locations.sections': {}, 'locations.people': {}, }, }, }) @Controller('mexico/municipality') export class MunicipalityController implements CrudController<MunicipalityEntity> { constructor(public service: MunicipalityService) { } } <file_sep>import { Role } from '../entities/role.entity'; declare const routes: Role[]; export default routes; <file_sep>import * as bcrypt from 'bcrypt'; import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { PayloadToken } from '../common/types/jwt'; import { UserEntity } from '../user/user.entity'; import { UserService } from '../user/user.service'; interface UserBody { name: string; email: string; passw: string; lastnameFather: string; lastnameMother: string; department: number; role: number; campus: number; status: number; } @Injectable() export class AuthService { constructor( private readonly usersService: UserService, private readonly jwtService: JwtService, ) {} public async registerUserIfNotExist(userBody: UserBody): Promise<any> { const { name, email, passw, lastnameMother, lastnameFather, status, } = userBody; let user: UserEntity | undefined = await this.usersService.findOne({ where: { email }, }); if (user && (await bcrypt.compare(passw, user.password))) { const { password, ...result } = user; return result; } user = await this.usersService.save( await this.usersService.create({ lastname: lastnameFather + ' ' + lastnameMother, firstname: name, email, password: passw, }), ); if (user) { const { password, ...result } = user; return result; } return null; } async validateUser( email: string, passw: string, ): Promise<Partial<UserEntity> | null> { // const user: User | undefined = await this.usersService // .findOne({ email }, { // relations: [ // 'role', // 'campus', // 'department', // 'role.permissions', // 'role.permissions.route', // 'role.permissions.actions', // ], // }); const user: UserEntity | undefined = await this.usersService.repo .createQueryBuilder('users') .leftJoinAndSelect('users.role', 'role') .where('users.email = :email', { email }) .getOne(); if ( user && bcrypt.compareSync(passw, user.password.replace('<PASSWORD>$')) ) { const { password, ...result } = user; return result; } return null; } generateJWT( user: Partial<UserEntity>, ): { access_token: string; decode: PayloadToken | any } { const payload = { username: user.email, sub: user.id }; const token = this.jwtService.sign(payload); return { access_token: token, decode: this.jwtService.decode(token), }; } } <file_sep>import { Role } from '../roles/entities/role.entity'; import { LocationEntity } from '../location/location.entity'; export declare class UserEntity { id: number; firstname: string; lastname: string; email: string; password: string; role: Role; createdAt: Date; updatedAt: Date; people: LocationEntity; } <file_sep>import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from '../auth.service'; import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(readonly authService: AuthService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: true, // @ts-ignore secretOrKey: process.env.API_SECRET, }); } async validate(payload: any) { /*if (Date.now() >= payload.exp * 1000) { throw new UnauthorizedException('Expired token'); }*/ return payload; } } <file_sep>import { Controller, Get, UseGuards } from '@nestjs/common'; import { CountryService } from './country.service'; import { AuthGuard } from '@nestjs/passport'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Controller('country') export class CountryController { constructor(private readonly countryService: CountryService) {} @Get() @UseGuards(AuthGuard()) async findAll() { return await this.countryService.findAll(); } } <file_sep>import { AccessTokensEntity } from './accessTokens.entity'; import { Repository } from 'typeorm'; import { AcTokenDto } from './dto/AcToken.dto'; export declare class AccesstokensService { private readonly acTokensRepository; constructor(acTokensRepository: Repository<AccessTokensEntity>); createAccesToken(createuserDTO: AcTokenDto): Promise<any>; } <file_sep>import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; import { Action } from '../../actions/entities/action.entity'; import { Route } from '../../routes/entities/route.entity'; @Entity('route_action') export class RouteAction { @PrimaryGeneratedColumn({ type: 'int', }) id: number; @ManyToOne(type => Route, route => route.routeActions) route: Route; @ManyToOne(type => Action, action => action.routeActions) action: Action; } <file_sep>// import { RolEntity } from '../../roles/roles.entity'; export interface UserInterface { id: number; firstname: string; lastname: string; address: string; electorkey: string; telephone: string; email: string; password: string; updatedAt: Date; // id_rol?: RolEntity; } <file_sep>import { Permission } from '../../permissions/entities/permission.entity'; import { RouteAction } from '../../route-action/entities/route-action.entity'; export declare class Route { id: number; isActive: number; name: string; fatherID: number; level: number; url: string | null; icon: string; createdAt: Date; updatedAt: Date; permissions: Permission[]; routeActions: RouteAction[]; } <file_sep>import { SectionEntity } from '../section/section.entity'; import { LocationEntity } from '../location/location.entity'; import { UserEntity } from '../user/user.entity'; import { MunicipalityEntity } from '../municipality/municipality.entity'; import { StateEntity } from '../state/state.entity'; export declare enum TypeOfPeople { Lider = 1, Promovido = 2, Activista = 3 } export declare class CustomerEntity { id: number; name: string; lastNameFather: string | null; lastNameMother: string | null; clave: string | null; phone: string | null; direccion: string | null; peopleId: number | null; createdAt: Date; updatedAt: Date; typeOfPeople: TypeOfPeople; state: StateEntity; municipality: MunicipalityEntity; zona: LocationEntity; section: SectionEntity; user: UserEntity; facebook: string | null; instagram: string | null; twitter: string | null; email: string | null; voto: boolean; searchName: string; } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { Role } from './entities/role.entity'; import { RolesService } from './roles.service'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: Role, }, }) @Controller('system/roles') export class RolesController implements CrudController<Role> { constructor( readonly service: RolesService, ) { } get base(): CrudController<Role> { return this; } } <file_sep>import { MunicipalityService } from './municipality.service'; import { CrudController } from '@nestjsx/crud'; import { MunicipalityEntity } from './municipality.entity'; export declare class MunicipalityController implements CrudController<MunicipalityEntity> { service: MunicipalityService; constructor(service: MunicipalityService); } <file_sep>import { Injectable } from '@nestjs/common'; import { LocationEntity } from './location.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class LocationService extends TypeOrmCrudService<LocationEntity> { constructor(@InjectRepository(LocationEntity, DBNameConnection) repo) { super(repo); } async findAll(): Promise<LocationEntity[]> { return []; } } <file_sep>import { CountryService } from './country.service'; export declare class CountryController { private readonly countryService; constructor(countryService: CountryService); findAll(): Promise<import("./country.entity").CountryEntity[]>; } <file_sep>import { Connection, DataSource, QueryRunner } from 'typeorm'; import { Factory, Seeder, times } from 'typeorm-seedling'; import { Role } from '../entities/role.entity'; import routes from './role.catalogue'; export default class RoleInsertUpdateSeed implements Seeder { public async run(factory: Factory, connection: QueryRunner): Promise<any> { await connection.connection .createQueryBuilder() .insert() .into(Role) .values(routes) .execute(); } } <file_sep>import { CONFIG_DB_CONFIG } from '../../config/config.constants'; import { ConfigService } from '@nestjs/config'; import { ConnectionOptions } from 'typeorm'; import { DBNameConnection } from '../../config/database.config'; import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRootAsync({ name: DBNameConnection, async useFactory(configService: ConfigService) { return configService.get(CONFIG_DB_CONFIG); }, inject: [ConfigService], }), ], exports: [], }) export class DatabaseModule {} <file_sep>import { Response } from 'express'; import { AuthService } from './auth.service'; import { RolesService } from '../roles/roles.service'; export declare class AuthController { readonly authService: AuthService; readonly roleService: RolesService; constructor(authService: AuthService, roleService: RolesService); login(req: any, res: Response): Promise<void>; register(req: any, res: Response): Promise<void>; logout(req: any, res: any): void; getJWT(req: any, res: Response): void; checkMySession(req: any, res: Response): void; } <file_sep>import { ConfigModule as ConfigModulePackage } from "@nestjs/config"; import { Module } from "@nestjs/common"; import configSchema from "../../config/config.schema"; import databaseConfig from "../../config/database.config"; import serverConfig from "../../config/server.config"; @Module({ imports: [ ConfigModulePackage.forRoot({ ignoreEnvFile: process.env.NODE_ENV === "production", envFilePath: `environment/.env.${process.env.NODE_ENV || "development"}`, load: [serverConfig, databaseConfig], validationSchema: configSchema, isGlobal: true, }), ], }) export class ConfigModule {} <file_sep>import { Controller, Get, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { StateEntity } from './state.entity'; import { StateService } from './state.service'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: StateEntity, }, query: { join: { country: {}, municipalitys: {}, }, }, }) @Controller('mexico/state') export class StateController implements CrudController<StateEntity> { constructor(public service: StateService) { } @Get() async findAll() { return await this.service.findAll(); } } <file_sep>import { UserEntity } from '../user.entity'; declare const users: Partial<UserEntity>[]; export default users; <file_sep>import { Role } from 'src/roles/entities/role.entity'; import { UserEntity } from '../user.entity'; const users: Partial<UserEntity>[] = [ { id: 1, email: '<EMAIL>', firstname: 'Admin', lastname: 'Polaca', role: { id: 1, } as Role, password: '<PASSWORD>', people: null, } as UserEntity, { id: 2, email: '<EMAIL>', firstname: 'amir', lastname: 'marin', role: { id: 1, } as Role, password: '<PASSWORD>', people: null, } as UserEntity, ] as Partial<UserEntity>[]; export default users; <file_sep>import { DBNameConnection } from '../config/database.config'; import { ElectionController } from './election.controller'; import { ElectionEntity } from './election.entity'; import { ElectionService } from './election.service'; import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([ElectionEntity], DBNameConnection)], providers: [ElectionService], controllers: [ElectionController], }) export class ElectionModule {} <file_sep>export declare class AccessTokensEntity { id: number; user_id: number; name: string; token: string; revoked: boolean; createdAt: Date; updatedAt: Date; expiresAt: string; } <file_sep>import { JwtService } from '@nestjs/jwt'; import { PayloadToken } from '../common/types/jwt'; import { UserEntity } from '../user/user.entity'; import { UserService } from '../user/user.service'; interface UserBody { name: string; email: string; passw: string; lastnameFather: string; lastnameMother: string; department: number; role: number; campus: number; status: number; } export declare class AuthService { private readonly usersService; private readonly jwtService; constructor(usersService: UserService, jwtService: JwtService); registerUserIfNotExist(userBody: UserBody): Promise<any>; validateUser(email: string, passw: string): Promise<Partial<UserEntity> | null>; generateJWT(user: Partial<UserEntity>): { access_token: string; decode: PayloadToken | any; }; } export {}; <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { CustomerEntity } from './customer.entity'; import { Repository } from 'typeorm'; export declare class CustomerService extends TypeOrmCrudService<CustomerEntity> { readonly repo: Repository<CustomerEntity>; constructor(repo: Repository<CustomerEntity>); } <file_sep>import { StateEntity } from '../state/state.entity'; export declare class CountryEntity { id: number; abrev: string; name: string; cod_tel: string; states: StateEntity[]; createdAt: Date; updatedAt: Date; } <file_sep>export declare class CreateUserDTO { readonly firstname: string; readonly lastname: string; readonly address: string; readonly electorkey: string; readonly telephone: string; readonly email: string; password: string; readonly confirm_password: string; } <file_sep>import { RouteAction } from '../entities/route-action.entity'; declare const routesActions: RouteAction[]; export default routesActions; <file_sep>import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Role } from './entities/role.entity'; import { Repository } from 'typeorm'; export declare class RolesService extends TypeOrmCrudService<Role> { constructor(repo: Repository<Role>); getPermissionRol(id: number): Promise<Role>; } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { SectionService } from './section.service'; import { SectionEntity } from './section.entity'; import { Crud, CrudController } from '@nestjsx/crud'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: SectionEntity, }, query: { join: { state: {}, municipality: {}, location: {}, people: {}, }, }, }) @Controller('section') export class SectionController implements CrudController<SectionEntity> { constructor(public service: SectionService) { } } <file_sep>export declare class ElectionController { } <file_sep>export declare class MunicipalityModule { } <file_sep>import { Strategy } from 'passport-local'; import { AuthService } from '../auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { constructor(private readonly authService: AuthService) { super({ usernameField: 'email', passReqToCallback: false, }); } async validate(email, password, done: (err: any, user: any) => void) { await this.authService.validateUser(email, password) .then(user => done(null, user)) .catch(err => done(err, false)); } } <file_sep>import { Permission } from '../entities/permission.entity'; declare const permission: Permission[]; export default permission; <file_sep>import * as Joi from '@hapi/joi'; const Schema = Joi.object({ NODE_ENV: Joi.string() .valid('development', 'pre-production', 'production') .default('development'), PORT: Joi.number().default(3000), JWT_SECRET: Joi.string(), JWT_EXPIRATION: Joi.string(), DB_PORT: Joi.number(), EMAIL_HOST: Joi.string(), EMAIL_PORT: Joi.number(), EMAIL_SECURE: Joi.boolean(), EMAIL_USER: Joi.string(), EMAIL_PASS: Joi.string(), EMAIL_DEFAULT_FROM_NAME: Joi.string(), EMAIL_DEFAULT_FROM_EMAIL: Joi.string(), }); export default Schema; <file_sep>import { Route } from '../entities/route.entity'; // @ts-ignore const routes: Route[] = [ { id: 1, isActive: 1, name: 'Dashboard', fatherID: null, level: 1, url: '/', icon: 'mdi-home', }, { id: 2, isActive: 1, name: 'Personas', fatherID: null, level: 2, url: '/people', icon: 'mdi-account-multiple', }, { id: 3, isActive: 1, name: 'votar', fatherID: null, level: 3, url: '/votar', icon: 'mdi-handshake', }, { id: 4, isActive: 1, name: 'Usuarios', fatherID: null, level: 4, url: '/usuarios', icon: 'mdi-account-circle', }, { id: 5, isActive: 1, name: 'Mexico', fatherID: null, level: 5, url: '', icon: 'mdi-mexico', }, { id: 6, isActive: 1, name: 'Estados', fatherID: 5, level: 6, url: '/estados', icon: 'mdi-badge-account-horizontal', }, { id: 7, isActive: 1, name: 'Municipios', fatherID: 5, level: 7, url: '/municipality', icon: 'mdi-account-details', }, { id: 8, isActive: 1, name: 'Zonas', fatherID: 5, level: 8, url: '/zonas', icon: 'mdi-google-maps', }, { id: 9, isActive: 1, name: 'Secciones', fatherID: 5, level: 9, url: '/secciones', icon: 'mdi-vector-intersection', }, { id: 10, isActive: 1, name: 'Configuracion', fatherID: null, level: 10, url: '', icon: 'mdi-cog-outline', }, { id: 11, isActive: 1, name: 'Roles', fatherID: 10, level: 1, url: '/roles', icon: 'mdi-axis-arrow-lock', }, { id: 12, isActive: 1, name: 'Base de Datos', fatherID: 10, level: 2, url: '/database', icon: 'mdi-database', }, ] as Route[]; export default routes; <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { SectionEntity } from './section.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class SectionService extends TypeOrmCrudService<SectionEntity> { constructor(@InjectRepository(SectionEntity, DBNameConnection) repo) { super(repo); } } <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Route } from './entities/route.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class RoutesService extends TypeOrmCrudService<Route> { constructor( @InjectRepository(Route, DBNameConnection) readonly repo: Repository<Route>, ) { super(repo); } public getRoots() { return this.repo.find(); } } <file_sep>export declare class PermissionDto { readonly roleId: number; readonly routeId: number; } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { Action } from './entities/action.entity'; import { ActionsService } from './actions.service'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: Action, }, }) @Controller() export class ActionsController implements CrudController<Action> { constructor( readonly service: ActionsService) { } get base(): CrudController<Action> { return this; } } <file_sep>import { CrudController } from '@nestjsx/crud'; import { Action } from './entities/action.entity'; import { ActionsService } from './actions.service'; export declare class ActionsController implements CrudController<Action> { readonly service: ActionsService; constructor(service: ActionsService); get base(): CrudController<Action>; } <file_sep>import { Controller, Get, UseGuards } from '@nestjs/common'; import { Crud, CrudController } from '@nestjsx/crud'; import { Route } from './entities/route.entity'; import { RoutesService } from './routes.service'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Crud({ model: { type: Route, }, query: { join: { 'routeActions': {}, 'routeActions.action': {}, 'permissions': {}, }, }, }) @Controller('system/routes') export class RoutesController implements CrudController<Route> { constructor( readonly service: RoutesService, ) { } get base(): CrudController<Route> { return this; } @Get('roots') async getRoots() { // return 'hola'; return await this.service.getRoots(); } } <file_sep>import { Controller, UseGuards } from '@nestjs/common'; import { JwtGuard } from '../auth/guards/jwt.guard'; @UseGuards(JwtGuard) @Controller('typelection') export class TypelectionController {} <file_sep>export declare class UpdatePasswordDto { readonly id: number; password: string; readonly passwordConfirm: string; } <file_sep>export declare class LocationModule { } <file_sep>export declare class AccesstokensController { } <file_sep>import { Action } from '../../actions/entities/action.entity'; import { Route } from '../../routes/entities/route.entity'; export declare class RouteAction { id: number; route: Route; action: Action; } <file_sep>export declare class VoteController { } <file_sep>export declare class ElectionModule { } <file_sep>import { LocationService } from './location.service'; import { CrudController } from '@nestjsx/crud'; import { LocationEntity } from './location.entity'; export declare class LocationController implements CrudController<LocationEntity> { service: LocationService; constructor(service: LocationService); } <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Route } from '../routes/entities/route.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { RouteAction } from './entities/route-action.entity'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class RouteActionService extends TypeOrmCrudService<RouteAction> { constructor( @InjectRepository(RouteAction, DBNameConnection) readonly repo: Repository<RouteAction>, ) { super(repo); } } <file_sep>import { Route } from '../entities/route.entity'; declare const routes: Route[]; export default routes; <file_sep>import { QueryRunner } from 'typeorm'; import { Factory, Seeder } from 'typeorm-seedling'; export default class RouteActionInsertUpdateSeed implements Seeder { run(factory: Factory, connection: QueryRunner): Promise<any>; } <file_sep>import { Action } from '../entities/action.entity'; // @ts-ignore const actions: Array<Partial<Action>> = [ { id: 1, name: 'CREATE', // @ts-ignore description: 'Permite la creacion de cualquier valor en el modulo selecionado', icon: '', isDefault: true, }, { id: 2, name: 'READ', // @ts-ignore description: 'Permite ver cualquier valor en el modulo selecionado', icon: '', isDefault: true, }, { id: 3, name: 'UPDATE', // @ts-ignore description: 'Permite la actualizacion de cualquier valor en el modulo selecionado', icon: '', isDefault: true, }, { id: 4, name: 'DELETE', // @ts-ignore description: 'Permite la eliminacion de cualquier valor en el modulo selecionado siempre y cuando se permita por el sistema', icon: '', isDefault: true, }, ]; export enum ActionsEnum { CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4, } export default actions; <file_sep>import { Action } from './entities/action.entity'; import { ActionsController } from './actions.controller'; import { ActionsService } from './actions.service'; import { DBNameConnection } from '../config/database.config'; import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [TypeOrmModule.forFeature([Action], DBNameConnection)], exports: [ActionsService], controllers: [ActionsController], providers: [ActionsService], }) export class ActionsModule {} <file_sep>import { CountryEntity } from './country.entity'; import { Repository } from 'typeorm'; export declare class CountryService { private readonly countryRepository; constructor(countryRepository: Repository<CountryEntity>); findAll(): Promise<CountryEntity[]>; } <file_sep>declare const Schema: any; export default Schema; <file_sep>import { Column, Entity, ManyToMany, OneToMany, PrimaryGeneratedColumn, JoinTable, Tree, TreeChildren, TreeParent } from 'typeorm'; import { Permission } from '../../permissions/entities/permission.entity'; import { Action } from '../../actions/entities/action.entity'; import { RouteAction } from '../../route-action/entities/route-action.entity'; @Entity('route') export class Route { @PrimaryGeneratedColumn({ type: 'int', }) id: number; @Column('tinyint', { nullable: false, }) isActive: number; @Column('varchar', { nullable: false, length: 60, }) name: string; @Column('int', { nullable: true, }) fatherID: number; @Column('int', { nullable: false, }) level: number; @Column('varchar', { nullable: true, }) url: string | null; @Column('varchar', { nullable: false, length: 50, }) icon: string; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) createdAt: Date; @Column('timestamp', { nullable: false, default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP', }) updatedAt: Date; @OneToMany(() => Permission, (permission) => permission.route) permissions: Permission[]; @OneToMany(type => RouteAction, routeAction => routeAction.route) routeActions: RouteAction[]; } <file_sep>export declare class CountryModule { } <file_sep>import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtGuard extends AuthGuard('jwt') { canActivate(context: ExecutionContext) { // Add your custom authentication logic here // for example, call super.logIn(request) to establish a session // throw new UnauthorizedException(); return super.canActivate(context); } handleRequest(err: any, user: any, info: any, context: ExecutionContext, status?: any) { console.log('JWT'); // You can throw an exception based on either "info" or "err" arguments if (err || !user) { throw err || new UnauthorizedException(); } if (!context.switchToHttp().getRequest().headers.authorization) { throw err || new UnauthorizedException(); } const token = context.switchToHttp().getRequest().headers.authorization.replace('Bearer ', ''); if (Date.now() >= user.exp * 1000) { throw err || new UnauthorizedException('Expired token'); } return user; } } <file_sep>export declare class StateModule { } <file_sep>import { Injectable } from '@nestjs/common'; import { TypeOrmCrudService } from '@nestjsx/crud-typeorm'; import { Role } from './entities/role.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { DBNameConnection } from '../config/database.config'; @Injectable() export class RolesService extends TypeOrmCrudService<Role> { constructor( @InjectRepository(Role, DBNameConnection) repo: Repository<Role>, ) { super(repo); } async getPermissionRol(id: number) { const permission = await this.repo .createQueryBuilder('role') .leftJoinAndSelect('role.permissions', 'permissions') .leftJoinAndSelect('permissions.route', 'route') .leftJoinAndSelect('permissions.actions', 'actions') .where('role.id = :id', { id }) .getOne(); return permission; } } <file_sep>export declare const DBNameConnection = "ine"; declare const _default: (() => { config: import("typeorm").DataSourceOptions; }) & import("@nestjs/config").ConfigFactoryKeyHost<{ config: import("typeorm").DataSourceOptions; }>; export default _default; <file_sep>import { Global, Module } from '@nestjs/common'; import { AccessTokensEntity } from './accessTokens.entity'; import { AccesstokensController } from './accesstokens.controller'; import { AccesstokensService } from './accesstokens.service'; import { DBNameConnection } from '../config/database.config'; import { TypeOrmModule } from '@nestjs/typeorm'; @Global() @Module({ imports: [TypeOrmModule.forFeature([AccessTokensEntity], DBNameConnection)], providers: [AccesstokensService], controllers: [AccesstokensController], exports: [AccesstokensService], }) export class AccesstokensModule {} <file_sep>import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm'; import { StateEntity } from '../state/state.entity'; @Entity('country') export class CountryEntity { @PrimaryGeneratedColumn() id: number; @Column() abrev: string; @Column() name: string; @Column() cod_tel: string; @OneToMany(type => StateEntity, state => state.country) states: StateEntity[]; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @Column('timestamp', { default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; }
66c1afbe0c1b4edf72e3cdbd595b5249b9258e37
[ "TypeScript" ]
157
TypeScript
MisaelMa/elections
1170ee66e3668a6fae3d4b4787b952fd2b46cd86
e63171e53a85e9d17e31f283ded1004f0f5d0de6
refs/heads/master
<repo_name>alaa-alqisi/rbk3-self-assessment-week3v3<file_sep>/backbone-pond/fishModel.js // Please modify this file! var Fish = Backbone.Model.extend({ defaults: { name: 'Larry', image: 'http://www.google.com', description: 'Regular old fish', displayInfo: false }, toggleDescription:function () { var x =this.get('displayInfo'); this.set('displayInfo',!x); this.trigger('toggle:description',this.render,this) }, render:function(){ defaults.description.$el.append('<tr>') } });
261ce7183f69a3fab3358d3a73cef9314fa98558
[ "JavaScript" ]
1
JavaScript
alaa-alqisi/rbk3-self-assessment-week3v3
3f6b4f36561ad161e8d83df4480e9c83efb55c16
b6c468833f31f0813163ccc8e151bfe775fb63bf
refs/heads/master
<file_sep>package com.main.sts.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.Users_RolesDao; import com.main.sts.entities.Users_Roles; @Service public class Users_RolesService { @Autowired private Users_RolesDao users_RolesDao; public void insertIntoUsers_roles(Users_Roles users_roles) { users_RolesDao.insertIntoUser_Roles(users_roles); } public Users_Roles getUserByUserId(int user_id) { return users_RolesDao.getUserByUserId(user_id); } public void updateUsersRoles(int user_id,int role_id) { Users_Roles ur=users_RolesDao.getUserByUserId(user_id); ur.setRole_id(role_id); users_RolesDao.updateUser_Roles(ur); } public boolean deleteUser_roles(int user_id) { try{ Users_Roles ur=getUserByUserId(user_id); users_RolesDao.deleteUser(ur); return true; } catch(Exception e) { e.printStackTrace(); return false; } } } <file_sep>package com.main.sts; import java.util.List; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.dto.BookingDTO; import com.main.sts.dto.response.BookingCancellationResponse; import com.main.sts.dto.response.BookingResponse; import com.main.sts.dto.response.CommuterBookingResponse; import com.main.sts.dto.response.CommuterResponse; import com.main.sts.dto.response.PreBookingDetails; import com.main.sts.dto.response.StopsResponseDTO; import com.main.sts.entities.Booking; import com.main.sts.entities.BookingWebDTO; import com.main.sts.service.BookingService; public class BookingServiceTest extends BaseTest { @Resource private BookingService bookingService; @Test public void testFindAll() { Assert.assertFalse(bookingService.findAll().isEmpty()); for (Booking c : bookingService.findAll()) { System.out.println(c.getBus_id() + "--" + c.getBooking_travel_date() + "--" + c.getBooking_travel_date_time()); } } @Test public void testBookNow() { // Assert.assertFalse(bookingService.findAll().isEmpty()); String email = "<EMAIL>"; String mobile = "919908599937"; int commuter_id = 766; // int trip_id = 6634; int trip_id = 234; // route_id= 12656 // trip_id = 13496 Integer from_stop_code = 33;//127; Integer to_stop_code = 34;//130;// 34; BookingDTO booking = new BookingDTO(); booking.setCommuter_id(commuter_id); booking.setTrip_id(trip_id); booking.setFrom_stop_id(from_stop_code); booking.setTo_stop_id(to_stop_code); booking.setNum_seats_choosen(1); boolean bookingMsgToBeSent = false; BookingResponse bookingResp = null; try { bookingResp = bookingService.bookNow(booking, bookingMsgToBeSent); } catch (Exception e) { e.printStackTrace(); } Assert.assertNotNull(bookingResp); System.out.println("bookingResp:" + bookingResp); } @Test public void testCancelRideNow() { // Assert.assertFalse(bookingService.findAll().isEmpty()); int booking_id = 1387;//1410;//53; BookingCancellationResponse bookingCancellationResp = null; try { bookingCancellationResp = bookingService.cancelRide(booking_id); } catch (Exception e) { e.printStackTrace(); } Assert.assertNotNull(bookingCancellationResp); System.out.println("bookingCancellationResp:" + bookingCancellationResp); } @Test public void testPreBookingDetails() { int commuter_id = 101;//742;//1; // int trip_id = 6634; int trip_id = 1;//2; int num_seats_choosen =1 ; // trip_id = 7610; // route_id= 12656 // trip_id = 13496 Integer source_stop_id = 33;//14;//33;// 130;//127; Integer dest_stop_id = 34;//4;//34;// 127;//130;// 34; try { PreBookingDetails preBookingDetails = bookingService.getPreBookingDetails(commuter_id, num_seats_choosen, trip_id, source_stop_id, dest_stop_id); System.out.println(preBookingDetails); for (StopsResponseDTO rs : preBookingDetails.getStops()) { System.out.println(rs); } } catch (Exception e) { e.printStackTrace(); } } @Test public void testAllCommutersInATrip() { int trip_id = 2; List<CommuterBookingResponse> list = bookingService.getAllCommuters(trip_id); Assert.assertNotNull(list); Assert.assertNotSame(0, list.size()); for (CommuterBookingResponse cbr : list) { System.out.println(cbr.getStop_name()); for (CommuterResponse c : cbr.getCommuters()) { System.out.println("\t" + c.getBooking_id()+"--"+c.getCommuter_name() + "--" + c.getPickup_stop_id() +"--"+c.getType()); } } } @Test public void testSendASMSBookingConfirmation(){ int booking_id = 62752; // Note: its important. boolean bookingMsgToBeSent = false; Booking booking = bookingService.getBookingById(booking_id); bookingService.sendBookingConfirmationSMS(booking, bookingMsgToBeSent); } @Test public void testBookingCancellationSMS(){ int booking_id = 62752; // Note: its important. boolean bookingMsgToBeSent = false; Booking booking = bookingService.getBookingById(booking_id); bookingService.sendBookingCancellationSMS(booking, bookingMsgToBeSent); } @Test public void testMarkBookingExpired(){ int trip_id = 226; // Note: its important. boolean sendEnabled = true; bookingService.markBookingExpired(trip_id, sendEnabled); } @Test public void testGetAllBookingDetailsWithCommuters(){ List<BookingWebDTO> bookings = bookingService.getBookingWithCommuterDetails(); for (BookingWebDTO b : bookings) { System.out.println(b); } } } <file_sep>package com.main.sts.dto; import java.io.Serializable; import java.util.Date; public class GPSDataDTO implements Comparable<GPSDataDTO>, Serializable { // String vehicle_id; // vehicle number like AP284567 String gps_lat; String gps_long; // server side; Date tracking_event_time; public String getGps_lat() { return gps_lat; } public void setGps_lat(String gps_lat) { this.gps_lat = gps_lat; } public String getGps_long() { return gps_long; } public void setGps_long(String gps_long) { this.gps_long = gps_long; } @Override public int compareTo(GPSDataDTO o) { return this.tracking_event_time.compareTo(o.tracking_event_time); } @Override public String toString() { return "GPSDataDTO [gps_lat=" + gps_lat + ", gps_long=" + gps_long + ", tracking_event_time=" + tracking_event_time + "]"; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.main.sts.entities.Address; import com.main.sts.entities.Alerts; import com.main.sts.entities.Staff; import com.main.sts.entities.Transport; import com.main.sts.util.StaffJspEntity; @Repository public class StaffDao extends BaseDao { public void insert(Staff staff) { insertEntity(staff); } public List<Staff> getStaff() { return getAllRecords(Staff.class); } public void insertAlert(Alerts alerts) { insertEntity(alerts); } public void insertTransport(Transport transport) { insertEntity(transport); } public void insertAddress(Address address) { insertEntity(address); } public Staff getstaff(String staff_id) { String query = "from Staff where staff_id=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, staff_id); return getSingleRecord(Staff.class, query, parameter); } public Staff getStaff(int id) { String query = "from Staff where id=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, id); return getSingleRecord(Staff.class, query, parameter); } public Address getAddress(int subscriber_id, String type) { String query = "from Address where subscriber_id=? and subscriber_type=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, subscriber_id); parameter.put(1, type); return getSingleRecord(Address.class, query, parameter); } public Transport getTransport(int subscriber_id, String trans_type) { String query = "from Transport where subscriber_id=? and transport_type=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, subscriber_id); parameter.put(1, trans_type); return getSingleRecord(Transport.class, query, parameter); } public Alerts getAlerts(int subscriber_id, String subscriber_type, String alert_type) { String query = "from Alerts b where b.subscriber_id=? and b.subscriber_type=? and b.alert_type=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, subscriber_id); parameters.put(1, subscriber_type); parameters.put(2, alert_type); return getSingleRecord(Alerts.class, query, parameters); } public void update(Staff staff) { updateEntity(staff); } public List<StaffJspEntity> getStaffDetails() { String query = "select s.id,s.full_name,s.rfid_number,s.mobile_number,s.staff_id,b.bus_licence_number as" + " bus_licence_number_home,b1.bus_licence_number as bus_licence_number_school," + "st.stop_name as stop_name_home ,st1.stop_name as stop_name_school from staff as s " + "LEFT JOIN transport as t on s.id = t.subscriber_id and t.transport_type='Pick Up' " + "LEFT JOIN transport as t1 on s.id = t1.subscriber_id and t1.transport_type='Drop Off' " + "LEFT JOIN buses as b on t.bus_id =b.bus_id " + " LEFT JOIN buses as b1 on t1.bus_id =b1.bus_id " + "LEFT JOIN stops as st on t.stop_id =st.id " + "LEFT JOIN stops as st1 on t1.stop_id =st1.id"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); return getStopsBySqlQuery(StaffJspEntity.class, query, parameter); } @SuppressWarnings("unchecked") @Transactional public <T> List<T> getStaffBySqlQuery(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { Session session = null; SQLQuery query = null; try { session = openSession(); query = session.createSQLQuery(queryStr); for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } query.addEntity(StaffJspEntity.class); List<StaffJspEntity> list = query.list(); return (List<T>) list; } catch (HibernateException e) { e.printStackTrace(); return null; } finally { session.close(); } } public List<StaffJspEntity> search(String column, String value) { Map< String, Object> restrictions=new HashMap<String, Object>(); restrictions.put("full_name", column); restrictions.put("rfid_number", "%" +value+ "%"); return searchRecords(StaffJspEntity.class, restrictions); } } <file_sep>package com.main.sts.controllers.webapp; import java.util.Arrays; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dto.FeedbackDTO; import com.main.sts.entities.Commuter; import com.main.sts.entities.Feedback; import com.main.sts.service.FeedbackService; @Controller @RequestMapping("/webapp/feedback") public class FeedbackWebAppController { @Autowired private FeedbackService feedbackService; static final Logger logger = Logger.getLogger(FeedbackWebAppController.class); @RequestMapping(value = "/show") public ModelAndView showFeedback(ModelAndView model) { model.setViewName("/webapp/feedback"); return model; } // @ApiOperation(value = "Submit the feedback about a trip") @RequestMapping(value = "/submit_feedback", method = RequestMethod.POST) public ModelAndView submitFeedback(ModelAndView model, HttpServletRequest request, HttpSession session) { boolean status = false; session = request.getSession(false); int commuter_id = ((Commuter)session.getAttribute("commuter")).getCommuter_id(); Integer trip_id = (Integer)session.getAttribute("trip_id"); int rating_points = Integer.parseInt(request.getParameter("rating")); String concern = request.getParameter("concern"); String[] reasons = (String[])request.getParameterValues("reason"); String reason = Arrays.toString(reasons); reason = reason.substring(1, reason.length()-1); try { Feedback feedbackObj = new Feedback(); feedbackObj.setCommuter_id(commuter_id); feedbackObj.setTrip_id(trip_id); feedbackObj.setRating_points(rating_points); feedbackObj.setReason(reason); feedbackObj.setConcern(concern); status = feedbackService.addFeedback(feedbackObj); model.addObject("status", status); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/feedback"); return model; } } <file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="plexus_mediator_record") public class PlexusMediatorRecord { @Id @GeneratedValue private int id; private int student_id; private String person_name,message,date,time,mobile_number,notification_id,status,device_type; public int getId() { return id; } public int getStudent_id() { return student_id; } public String getPerson_name() { return person_name; } public String getMessage() { return message; } public String getDate() { return date; } public String getTime() { return time; } public String getMobile_number() { return mobile_number; } public String getNotification_id() { return notification_id; } public String getStatus() { return status; } public String getDevice_type() { return device_type; } public void setId(int id) { this.id = id; } public void setStudent_id(int student_id) { this.student_id = student_id; } public void setPerson_name(String person_name) { this.person_name = person_name; } public void setMessage(String message) { this.message = message; } public void setDate(String date) { this.date = date; } public void setTime(String time) { this.time = time; } public void setMobile_number(String mobile_number) { this.mobile_number = mobile_number; } public void setNotification_id(String notification_id) { this.notification_id = notification_id; } public void setStatus(String status) { this.status = status; } public void setDevice_type(String device_type) { this.device_type = device_type; } @Override public String toString() { return "PlexusMediatorRecord [id=" + id + ", student_id=" + student_id + ", person_name=" + person_name + ", message=" + message + ", date=" + date + ", time=" + time + ", mobile_number=" + mobile_number + ", notification_id=" + notification_id + ", status=" + status + ", device_type=" + device_type + "]"; } } <file_sep>package com.main.sts.entities; import java.util.Calendar; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "trips") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "trips") public class Trips implements Comparable<Trips> { @Id //@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "trips_id_seq_gen") @SequenceGenerator(name = "trips_id_seq_gen", sequenceName = "trips_id_seq") private int id; private int trip_detail_id; private int seats_filled; private Date trip_running_date; private Boolean enabled = true; @OneToOne(targetEntity = TripDetail.class) @JoinColumn(name = "trip_detail_id", referencedColumnName = "id", insertable = false, updatable = false) @BatchSize(size = 20) private TripDetail tripDetail; @Transient private boolean active = true; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTrip_detail_id() { return trip_detail_id; } public void setTrip_detail_id(int trip_detail_id) { this.trip_detail_id = trip_detail_id; } public TripDetail getTripDetail() { return tripDetail; } public void setTripDetail(TripDetail tripDetail) { this.tripDetail = tripDetail; } public int getSeats_filled() { return seats_filled; } public void setSeats_filled(int seats_filled) { this.seats_filled = seats_filled; } public Date getTrip_running_date() { return trip_running_date; } public void setTrip_running_date(Date trip_running_date) { this.trip_running_date = trip_running_date; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public int compareTo(Trips o) { return this.trip_running_date.compareTo(o.trip_running_date); } public Date getTripRunningTime() { return getTripRunningTimeCal().getTime(); } public Calendar getTripRunningTimeCal() { Trips t = this; TripDetail td = t.getTripDetail(); System.out.println("trip:" + td.getTrip_name() + "---" + t.getTrip_running_date()); Calendar tripRunningTime = Calendar.getInstance(); tripRunningTime.setTime(t.getTrip_running_date()); tripRunningTime.set(Calendar.HOUR_OF_DAY, td.getTrip_start_time_hours()); tripRunningTime.set(Calendar.MINUTE, td.getTrip_start_time_minutes()); tripRunningTime.set(Calendar.SECOND, 0); tripRunningTime.set(Calendar.MILLISECOND, 0); return tripRunningTime; } @Override public String toString() { return "Trips [id=" + id + ", trip_detail_id=" + trip_detail_id + ", seats_filled=" + seats_filled + ", trip_running_date=" + trip_running_date + ", enabled=" + enabled + ", tripDetail=" + tripDetail + "]"; } } <file_sep>package com.main.sts.model; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class HomePageDataEntity { @Bean public HomePageDataEntity homePageDataEntity(){ return new HomePageDataEntity(); } private String bus_licence; private String bus_id; private String current_stop; private String arrived_time; private int no_of_students; private String driver_id; private String driver_name; private String status; public String getBus_licence() { return bus_licence; } public void setBus_licence(String bus_licence) { this.bus_licence = bus_licence; } public String getBus_id() { return bus_id; } public void setBus_id(String bus_id) { this.bus_id = bus_id; } public String getCurrent_stop() { return current_stop; } public void setCurrent_stop(String current_stop) { this.current_stop = current_stop; } public String getArrived_time() { return arrived_time; } public void setArrived_time(String arrived_time) { this.arrived_time = arrived_time; } public int getNo_of_students() { return no_of_students; } public void setNo_of_students(int no_of_students) { this.no_of_students = no_of_students; } public String getDriver_id() { return driver_id; } public void setDriver_id(String driver_id) { this.driver_id = driver_id; } public String getDriver_name() { return driver_name; } public void setDriver_name(String driver_name) { this.driver_name = driver_name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() { return "HomePageDataEntity [bus_licence=" + bus_licence + ", bus_id=" + bus_id + ", current_stop=" + current_stop + ", arrived_time=" + arrived_time + ", no_of_students=" + no_of_students + ", driver_id=" + driver_id + ", driver_name=" + driver_name + ", status=" + status + "]"; } } <file_sep>package com.main.sts.dto; public class RegisterNotifyAvailabilityDTO { int trip_id; int commuter_id; int from_stop_id; int to_stop_id; public int getTrip_id() { return trip_id; } public void setTrip_id(int trip_id) { this.trip_id = trip_id; } public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public int getFrom_stop_id() { return from_stop_id; } public void setFrom_stop_id(int from_stop_id) { this.from_stop_id = from_stop_id; } public int getTo_stop_id() { return to_stop_id; } public void setTo_stop_id(int to_stop_id) { this.to_stop_id = to_stop_id; } } <file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="alerts") public class Alerts { @Id @GeneratedValue private Integer id; private String subscriber_type; private String alert_type; private String all_alerts; private String no_show; private String late; private String irregularities; private String regularities; private Integer subscriber_id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSubscriber_type() { return subscriber_type; } public void setSubscriber_type(String subscriber_type) { this.subscriber_type = subscriber_type; } public String getAlert_type() { return alert_type; } public void setAlert_type(String alert_type) { this.alert_type = alert_type; } public String getAll_alerts() { return all_alerts; } public void setAll_alerts(String all_alerts) { this.all_alerts = all_alerts; } public String getNo_show() { return no_show; } public void setNo_show(String no_show) { this.no_show = no_show; } public String getLate() { return late; } public void setLate(String late) { this.late = late; } public String getIrregularities() { return irregularities; } public void setIrregularities(String irregularities) { this.irregularities = irregularities; } public String getRegularities() { return regularities; } public void setRegularities(String regularities) { this.regularities = regularities; } public Integer getSubscriber_id() { return subscriber_id; } public void setSubscriber_id(Integer subscriber_id) { this.subscriber_id = subscriber_id; } @Override public String toString() { return "Alerts [id=" + id + ", subscriber_type=" + subscriber_type + ", alert_type=" + alert_type + ", all_alerts=" + all_alerts + ", no_show=" + no_show + ", late=" + late + ", irregularities=" + irregularities + ", regularities=" + regularities + ", subscriber_id=" + subscriber_id + "]"; } } <file_sep>package com.main.sts.controllers.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.main.sts.dto.Response; import com.main.sts.dto.SavedRouteDTO; import com.main.sts.dto.SavedRouteResponse; import com.main.sts.service.ReturnCodes; import com.main.sts.service.SavedRoutesService; @Controller @RequestMapping("/routes") public class SavedRouteController { @Autowired private SavedRoutesService savedRoutesService; @RequestMapping(value = "/save_route", method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> saveTheRoute(@RequestBody SavedRouteDTO savedRoute) { Response resp = new Response(); ReturnCodes returnCode = null; try { returnCode = savedRoutesService.saveARoute(savedRoute); resp.response = null; resp.returnCode = returnCode.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.response = null; resp.returnCode = returnCode.name(); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } @RequestMapping(value = "/getSavedRoutesByCommuterId/{commuter_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> getSavedRoutesByCommuterId(@PathVariable Integer commuter_id) { Response resp = new Response(); List<SavedRouteResponse> list = null; try { list = savedRoutesService.getAllSavedRoutesResponse(commuter_id); resp.response = list; return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { resp.response = null; return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.Buses; import com.main.sts.entities.Drivers; import com.main.sts.service.BusesService; import com.main.sts.service.DriversService; import com.main.sts.service.StudentsService; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/bus") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class BusesController { @Autowired private StudentsService studentservice; @Autowired private RolesUtility usersUtility; // new dependencies private static final Logger logger = Logger.getLogger(BusesController.class); @Autowired private BusesService busesservice; @Autowired private DriversService driverservie; @RequestMapping(value = "/buses", method = RequestMethod.GET) public ModelAndView driversHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus/buses_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); /* * List<TripEntity> trips=tripsDaoImpl.getAllTrips(); for (TripEntity * tripEntity : trips) { int seats=tripEntity.getTotal_seats(); * if(seats>0) { String busLicence=tripEntity.getBus_id(); * busesDaoImpl.updateBusAllottedSeas(busLicence); } } */ model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); List<Buses> buses = busesservice.getBuses(); Collections.sort(buses); model.addObject("buses", buses); // System.out.println(buses); // getting count of student in buslist model.addObject("login_role", usersUtility.getRole(request)); return model; } @RequestMapping(value = "/add", method = RequestMethod.GET) public ModelAndView seniorHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/bus/addnewbus"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("drivers", driverservie.listDrivers()); // System.out.println(driverservie.listDrivers()); model.addObject("login_role", usersUtility.getRole(request)); return model; } @RequestMapping(value = "/addbusaction", method = RequestMethod.POST) public ModelAndView addBusAction(ModelAndView model, HttpServletRequest request, @ModelAttribute Buses busEntity) { if (request.isUserInRole("ROLE_ADMIN")) { model.addObject("login_role", "ROLE_ADMIN"); } Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // System.out.println(busEntity); Buses bus = busesservice.getBusByLicence(busEntity.getBus_licence_number()); if (bus != null) { model.setViewName("/school_admin/bus/addnewbus"); model.addObject("login_role", usersUtility.getRole(request)); model.addObject("drivers", driverservie.listDrivers()); model.addObject("message", "bus_exists"); model.addObject("bus", busEntity); model.addObject("bus_licence_number", busEntity.getBus_licence_number()); return model; } int status = 1; int did = Integer.parseInt(request.getParameter("driver_name")); busEntity.setDriver(driverservie.getDriver(did)); busEntity.setDriverId(driverservie.getDriver(did).getId()); busesservice.insertBus(busEntity); driverservie.updateDriverStatus(did, status); // System.out.println(busEntity.getDriver().getDriver_name()); logger.info("New Bus [ " + busEntity.getBus_licence_number() + " ] got added"); return new ModelAndView("redirect:/school_admin/bus/buses"); } @RequestMapping(value = "/updatebus", method = RequestMethod.GET) public ModelAndView updateBus(ModelAndView model, HttpServletRequest request, HttpSession session, @ModelAttribute Buses busEntity) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } int bus_id = Integer.parseInt(request.getParameter("id")); // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus/updatebus"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("drivers", driverservie.listDrivers()); // model.addObject("routes", routeDaoImpl.getAllRoutes()); model.addObject("date", formatter.format(new Date())); model.addObject("bus", busesservice.getBusById(bus_id)); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); // to store old bus stop. session.setAttribute("oldBusId", bus_id); // to store old driver id // Syste.mout.println("bus for update "+busEntity); model.addObject("login_role", usersUtility.getRole(request)); return model; } @RequestMapping(value = "/updatebusaction", method = RequestMethod.POST) public ModelAndView updateBusAction(ModelAndView model, HttpServletRequest request, HttpSession session, @ModelAttribute("busEntity") Buses busEntity) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // getting old bus details starts int oldBusId = (Integer) session.getAttribute("oldBusId"); Buses busOldEntity = busesservice.getBusById(oldBusId); // System.out.println(busOldEntity); String busOldLicence = busOldEntity.getBus_licence_number(); Buses check = busesservice.getBusByLicence(busEntity.getBus_licence_number()); if (check != null) if (check.getBus_id() != busOldEntity.getBus_id()) { // //System.out.println("busId equal"); // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus/updatebus"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); // model.addObject("buses", busesDaoImpl.getAllBuses()); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("bus", busesservice.getBusById(oldBusId)); model.addObject("drivers", driverservie.listDrivers()); model.addObject("login_role", usersUtility.getRole(request)); model.addObject("message", "bus_exists"); return model; } try { int did = 0; // System.out.println(request.getParameter("driver_name")); if (request.getParameter("driver_name").equals("") || request.getParameter("driver_name") == null) { // System.out.println("if"); busEntity.setDriver(driverservie.getDriver(busOldEntity.getDriver().getId())); busEntity.setDriverId(busOldEntity.getDriver().getId()); } else { // System.out.println("else"); did = Integer.parseInt(request.getParameter("driver_name")); busEntity.setDriver(driverservie.getDriver(did)); busEntity.setDriverId(did); driverservie.updateDriverStatus(busOldEntity.getDriver().getId(), 0); driverservie.updateDriverStatus(busEntity.getDriver().getId(), 1); } // System.out.println(busEntity); //shouldnt be uncommented as that will make it not to update the value of bus allotted. //busEntity.setBus_allotted(busOldEntity.getBus_allotted()); busesservice.updateBus(busEntity); logger.info("bus [ " + busEntity.getBus_licence_number() + " ] got updated by user [" + auth.getName() + " ]"); } catch (Exception e) { e.printStackTrace(); } /* * ////System.out.println("updatebusaction"); * busesDaoImpl.updateSingleBus(busEntity, oldBusId); //after update bus * licence number should be changed in trip * tripsDaoImpl.updateTripWhenBusUpdates(busOldLicence, * busEntity.getBus_licence_number(),busEntity.getBus_capacity()); * * //after updating the bus dirver availability has to change String * oldDriverId=busOldEntity.getDriver_id(); String * newDriverId=busEntity.getDriver_id(); * * if(!(oldDriverId.equals(newDriverId))) { * ////System.out.println("driver is changed"); * driverDaoImpl.updateDriverStatusWhenAddedToBus * (newDriverId,busEntity); * driverDaoImpl.updateDriverWhenBusDeleted(oldDriverId); } * * //if bus updates then it should update on student also * ////System.out.println(oldBusId); * studentDaoImpl.updateStudentBusLicenceFromHome(oldBusId, * busEntity.getBus_licence_number()); * studentDaoImpl.updateStudentBusLicenceFromSchool(oldBusId, * busEntity.getBus_licence_number()); * * //if bus updates then it should updateon staff also * staffDaoImpl.updateStaffBusLicenceFromHome(oldBusId, * busEntity.getBus_licence_number()); * staffDaoImpl.updateStaffBusLicenceFromSchool(oldBusId, * busEntity.getBus_licence_number()); */ model.addObject("login_role", usersUtility.getRole(request)); return new ModelAndView("redirect:/school_admin/bus/buses"); } @RequestMapping(value = "/removebus", method = RequestMethod.GET) public ModelAndView removeBus(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus/removebus"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); int busId = Integer.parseInt(request.getParameter("id")); Buses busEntity = busesservice.getBusById(busId); model.addObject("bus", busEntity); session.setAttribute("deletebusid", busId); model.addObject("login_role", usersUtility.getRole(request)); return model; } @RequestMapping(value = "/removebusaction", method = RequestMethod.POST) public ModelAndView RemoveBusAction(ModelAndView model, HttpServletRequest request, HttpSession session) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } /* String route_id=request.getParameter("route_id"); */ int busId = (Integer) session.getAttribute("deletebusid"); Buses bus = busesservice.getBusById(busId); int driver_id = bus.getDriver().getId(); // driverDaoImpl.updateDriverWhenBusDeleted(driver_id); if (bus.getBus_allotted() != 0) { model.setViewName("/school_admin/bus/removebus"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("bus", bus); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("error", "studentsExists"); model.addObject("login_role", usersUtility.getRole(request)); return model; } driverservie.updateDriverStatus(driver_id, 0); busesservice.deleteBus(busId); // routeDaoImpl.updateRouteWhenBusCreated(route_id, "none", "none"); // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); // //System.out.println("driverIDDDDD"+driver_id); model.addObject("login_role", usersUtility.getRole(request)); logger.info("bus [ " + bus.getBus_licence_number() + " ] got deleted"); return new ModelAndView("redirect:/school_admin/bus/buses"); } // search students starts @RequestMapping(value = "/search", method = RequestMethod.POST) public @ResponseBody String searchBusByBusId(HttpServletRequest request, Model model, HttpSession session) { String search_bus = request.getParameter("search_bus"); String searchOption = request.getParameter("searchOption"); System.out.println(search_bus + " " + searchOption); List<Buses> searchBuses = new ArrayList<Buses>(); if (searchOption.equals("bus_licence_number")) { searchBuses = busesservice.searchBuses(searchOption, search_bus); } else if (searchOption.equals("bus_capacity")) { searchBuses = busesservice.searchBuses(searchOption, search_bus); } else if (searchOption.equals("driverId")) { List<Drivers> drivers = driverservie.searchDrivers(search_bus, "driver_name"); // System.out.println(drivers); for (Drivers drivers2 : drivers) { Buses bus = busesservice.getBusByDriverId(drivers2.getId()); searchBuses.add(bus); } // System.out.println(searchBuses); } session.setAttribute("searchBuses", searchBuses); return "/sts/school_admin/bus/studentBus"; } @RequestMapping(value = "/studentBus", method = RequestMethod.GET) public ModelAndView studentSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus/buses_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); List<Buses> searchBusesList = (List<Buses>) session.getAttribute("searchBuses"); model.addObject("buses", searchBusesList); if (searchBusesList == null || searchBusesList.isEmpty()) { model.addObject("buses", busesservice.getBuses()); model.addObject("error_message", "noMatching"); } model.addObject("login_role", usersUtility.getRole(request)); return model; } // search students ends @RequestMapping(value = "/removeAllBusesByBusIds", method = RequestMethod.POST) public @ResponseBody String removeAllBusesByBusIds(ModelAndView model, HttpServletRequest request) { // //System.out.println("inside delete stops method"); String busIds = request.getParameter("busIds"); // //System.out.println(driverIds); String busIdsArray[] = busIds.split(","); int totalItems = busIdsArray.length; // //System.out.println(totalItems); for (int i = 0; i <= totalItems - 1; i++) { Buses busEntity = busesservice.getBusById(Integer.parseInt(busIdsArray[i])); // if this contain any student it should not be deleted. /* * Students student1 = studentservice. * .validateStudentByBusIdFromHome(busIdsArray[i]); StudentEntity * student2 = studentDaoImpl * .validateStudentByBusIdFromSchool(busIdsArray[i]); * * StaffEntity staff1 = staffDaoImpl * .validateStaffByBusIdFromHome(busIdsArray[i]); StaffEntity staff2 * = staffDaoImpl .validateStaffByBusIdFromSchool(busIdsArray[i]); * * TripEntity tripEntity = * tripsDaoImpl.validateTripByBusId(busEntity * .getBus_licence_number()); * * if (student1 == null && student2 == null && staff1 == null && * staff2 == null && tripEntity == null) { */ busesservice.deleteBus(Integer.parseInt(busIdsArray[i])); int status = busEntity.getDriver().getAvailable(); driverservie.updateDriverStatus(busEntity.getDriver().getId(), --status); // driverDaoImpl.updateDriverWhenBusDeleted(busEntity.getDriver_id()); } // return null; return "buses"; } @RequestMapping(value = "/unassign_driver", method = RequestMethod.GET) public ModelAndView assignDriver(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/bus//unassigndriver"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); int busId = Integer.parseInt(request.getParameter("id")); Buses busEntity = busesservice.getBusById(busId); model.addObject("bus", busEntity); session.setAttribute("deletebusid", busId); model.addObject("login_role", usersUtility.getRole(request)); return model; } @RequestMapping(value = "/unassigndriveraction", method = RequestMethod.POST) public ModelAndView assignDriverAction(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } /*int busId = Integer.parseInt(request.getParameter("bus_id")); Buses busEntity = busesservice.getBusById(busId); driverservie.updateDriverStatus(busEntity.getDriverId(), 0); busEntity.setDriver(null); busEntity.setDriverId(0); busesservice.updateBus(busEntity);*/ model.addObject("login_role", usersUtility.getRole(request)); model.setViewName("redirect:/school_admin/bus/buses"); return model; } }// class <file_sep>package com.main.sts.service; import java.util.Date; import javax.annotation.Resource; import org.junit.Test; import com.main.sts.BaseTest; import com.main.sts.common.CommonConstants.VehicleStatus; import com.main.sts.entities.DailyBusNotifications; import com.main.sts.util.DateUtil; public class DailyBusNotificationServiceTest extends BaseTest { @Resource private DailyBusNotificationService service; @Test public void testGetTodysNotifications() { Date today = DateUtil.getTodayDateWithOnlyDate(); for (DailyBusNotifications e : service.getTodysNotifications(today, VehicleStatus.ONTIME)) { System.out.println(e.getVehicle_id() + "--" + e); } } } <file_sep>package com.main.sts.controllers.webapp; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dto.Response; import com.main.sts.dto.response.ReferralDTO; import com.main.sts.entities.Commuter; import com.main.sts.entities.FAQ; import com.main.sts.entities.ReferralCode; import com.main.sts.service.ReferralCodeService; import com.main.sts.service.ReturnCodes; @Controller @RequestMapping("/webapp/referral") public class ReferralWebAppController extends CommonController{ @Autowired private ReferralCodeService referralCodeService; static final Logger logger = Logger.getLogger(ReferralWebAppController.class); @RequestMapping(value = "/generate") public ModelAndView createReferralCodeForACommuter(ModelAndView model, HttpServletRequest request, HttpSession session) { ReferralDTO referralCode = null; try { session = super.getSession(request); Commuter commuter = super.getCommuter(request); int commuter_id = commuter.getCommuter_id(); referralCode = referralCodeService.getReferralCode(commuter_id); model.addObject("referralCode", referralCode); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/refer&earn"); model.addObject("current_page", "refer&earn"); return model; } } <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.AdminEmailDao; import com.main.sts.entities.AdminEmails; @Service public class AdminEmailService { @Autowired private AdminEmailDao adminEmailDao; public List<AdminEmails> getAllMails() { return adminEmailDao.getAllMails(); } public void addEmail(String email){ AdminEmails adminEmails = new AdminEmails(); adminEmails.setEmail(email); adminEmailDao.addEmail(adminEmails); } public void deleteEmail(Integer id){ AdminEmails adminEmails = getMail(id); adminEmailDao.deleteEmail(adminEmails); } public AdminEmails getMail(Integer id){ return adminEmailDao.getSingleMail(id); } } <file_sep>package com.main.sts.entities; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "saved_routes") public class SavedRoutes { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "saved_routes_id_seq_gen") @SequenceGenerator(name = "saved_routes_id_seq_gen", sequenceName = "saved_routes_id_seq") private int id; private Integer commuter_id; private Integer from_stop_id; private Integer to_stop_id; private Integer pickup_time_hours; private Integer pickup_time_min; private Integer dropoff_time_hours; private Integer dropoff_time_min; private Date created_at; private Date updated_at; public int getId() { return id; } public void setId(int id) { this.id = id; } public Integer getPickup_time_hours() { return pickup_time_hours; } public void setPickup_time_hours(Integer pickup_time_hours) { this.pickup_time_hours = pickup_time_hours; } public Integer getPickup_time_min() { return pickup_time_min; } public void setPickup_time_min(Integer pickup_time_min) { this.pickup_time_min = pickup_time_min; } public Integer getDropoff_time_hours() { return dropoff_time_hours; } public void setDropoff_time_hours(Integer dropoff_time_hours) { this.dropoff_time_hours = dropoff_time_hours; } public Integer getDropoff_time_min() { return dropoff_time_min; } public void setDropoff_time_min(Integer dropoff_time_min) { this.dropoff_time_min = dropoff_time_min; } public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getFrom_stop_id() { return from_stop_id; } public void setFrom_stop_id(Integer from_stop_id) { this.from_stop_id = from_stop_id; } public Integer getTo_stop_id() { return to_stop_id; } public void setTo_stop_id(Integer to_stop_id) { this.to_stop_id = to_stop_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public Date getUpdated_at() { return updated_at; } public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; } @Override public String toString() { return "SavedRoutes [id=" + id + ", commuter_id=" + commuter_id + ", from_stop_id=" + from_stop_id + ", to_stop_id=" + to_stop_id + ", pickup_time_hours=" + pickup_time_hours + ", pickup_time_min=" + pickup_time_min + ", dropoff_time_hours=" + dropoff_time_hours + ", dropoff_time_min=" + dropoff_time_min + ", created_at=" + created_at + ", updated_at=" + updated_at + "]"; } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Properties; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dto.EmailDTO; import com.main.sts.dto.EmailResponse; import com.main.sts.entities.Buses; import com.main.sts.entities.Commuter; import com.main.sts.entities.DashboardSettings; import com.main.sts.entities.Parents; import com.main.sts.entities.Transport; import com.main.sts.entities.Trips; import com.main.sts.service.BusesService; import com.main.sts.service.CommuterService; import com.main.sts.service.DashBoardSettingsService; import com.main.sts.service.ParentService; import com.main.sts.service.SendGridMailProvider; import com.main.sts.service.TransportService; import com.main.sts.service.TripService; import com.main.sts.util.MD5PassEncryptionClass; import com.main.sts.util.MyThreadPoolExecutor; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/emails") @Secured("ROLE_ADMIN") @PreAuthorize("isAuthenticated()") public class EmailEvents { @Autowired //private ParentService studentservice; private CommuterService commuterService; Properties props = null; Session session = null; @Autowired private MD5PassEncryptionClass passwordEncrypt; @Autowired private RolesUtility rolesUtility; @Autowired private DashBoardSettingsService dashBoardSettingsService; @Autowired private TripService tripService; @Autowired private TransportService transportService; @Autowired private BusesService busesService; @Autowired private SendGridMailProvider emailProvider; // private DashboardSettings adminPreferences; private static final Logger logger = Logger.getLogger(EmailEvents.class); @RequestMapping(value = "/events", method = RequestMethod.GET) public ModelAndView getEvents(ModelAndView modelAndView, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { modelAndView.setViewName("redirect:/j_spring_security_logout"); return modelAndView; } System.out.println("getting events"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); modelAndView.addObject("date", formatter.format(new Date())); List<Buses> bus = busesService.getBuses(); modelAndView.addObject("allbuses", bus); modelAndView.setViewName("/school_admin/events/eventpage"); modelAndView.addObject("login_role", rolesUtility.getRole(request)); modelAndView.addObject("login_name", auth.getName()); return modelAndView; } @RequestMapping(value = "/getnames", method = RequestMethod.POST) public @ResponseBody String getNames(ModelAndView modelAndView, HttpServletRequest request) { String res = ""; String triptype = request.getParameter("busno"); int id = busesService.getBusByLicence(request.getParameter("busid")).getBus_id(); System.out.println("type " + triptype + " id " + id); List<Trips> list = null; if (triptype.contains(",")) { System.out.println("if"); String no[] = triptype.split(","); for (int i = 0; i < no.length; i++) { System.out.println(no[i]); list = tripService.getTripsByBusIdAndTripType(id, no[i]); System.out.println(list); for (Trips t : list) { res = res + t.getTripDetail().getTrip_name() + "+"; } } return res; } else { System.out.println("else"); list = tripService.getTripsByBusIdAndTripType(id, triptype); for (Trips t : list) { res = res + t.getTripDetail().getTrip_name() + "+"; } System.out.println(res); return res; } } @RequestMapping(value = "/send", method = RequestMethod.POST) public ModelAndView sendMail(HttpServletRequest request, ModelAndView model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } DashboardSettings adminPreferences = dashBoardSettingsService.getDashBoardSettings(); String event = request.getParameter("events"); String to = ""; String sub = request.getParameter("sub"); String body = request.getParameter("msg"); List<Commuter> commuters = null; if (event.equalsIgnoreCase("all")) { commuters = commuterService.findAll(); for (Commuter c : commuters) { to = to + c.getEmail() + ","; } } else if (event.equalsIgnoreCase("bus")) { String busid = request.getParameter("buses"); String trips[] = request.getParameterValues("tnames"); System.out.println("trip " + trips[0]); // basically it means it will send email to all the persons who were part of the selected trips on today. Date today = new Date(); today.setHours(0); today.setMinutes(0); today.setSeconds(0); for (int i = 0; i < trips.length; i++) { Trips trip = tripService.getTripByName(trips[i], today); List<Transport> sid = transportService.getCommuterIdByTrip(trip.getId()); for (Transport t : sid) { Commuter c = commuterService.getCommuterById(t.getSubscriber_id()); if (!to.contains(c.getEmail())) { to = to + c.getEmail() + ","; } } } } else if (event.equalsIgnoreCase("one")) { to = request.getParameter("email_id") + ","; } System.out.println("to:"+to); System.out.println("body:"+body); EmailDTO emailObj = new EmailDTO(); String[] tos = to.split(","); if (tos.length > 1) { tos = new String[]{"<EMAIL>", "<EMAIL>", "<EMAIL>"}; } boolean res = false; if (tos.length > 1) { emailObj.setTo(tos); emailObj.setSubject(sub); emailObj.setHtml(body); EmailResponse resp = emailProvider.sendEmail(emailObj); res = resp.getStatus(); } else { System.out.println("there are no participant for sending emails." + tos); res = false; } // System.out.println("result is "+res); model.addObject("login_role", rolesUtility.getRole(request)); model.setViewName("/school_admin/events/eventpage"); if (res) { model.addObject("result", "success"); } else { model.addObject("result", "failure"); } return model; } } <file_sep>package com.main.sts.service; public class SMSInfo { // String authKey; String mobile; // String senderId; String message; String route; // should Send messages are enabled? boolean sendEnabled = false; public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } public boolean isSendEnabled() { return sendEnabled; } public void setSendEnabled(boolean enabled) { this.sendEnabled = enabled; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import com.main.sts.common.CommonConstants; public class BookingWebDTO implements Comparable<BookingWebDTO>, Serializable { public int id; public int commuter_id; public int from_stop; public int to_stop; public int actual_fare; public int charged_fare; public Date booking_travel_date; public Date booking_time; public int num_seats_booked = 1; public int status; public int bus_id; public int trip_id; //public String booking_travel_date_time; public Date booking_expirary_date; public boolean message_sent_for_pickup; public boolean message_sent_for_dropoff; public Date booking_cancellation_date; // if a user try to book 4 person in one ticket, we will deduct 4 free // rides. public Integer charged_free_rides; public String commuter_name; public String mobile; public String gender; public String from_stop_name; public String to_stop_name; public String trip_name; public String trip_type; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public int getFrom_stop() { return from_stop; } public void setFrom_stop(int from_stop) { this.from_stop = from_stop; } public int getTo_stop() { return to_stop; } public void setTo_stop(int to_stop) { this.to_stop = to_stop; } public int getActual_fare() { return actual_fare; } public void setActual_fare(int actual_fare) { this.actual_fare = actual_fare; } public int getCharged_fare() { return charged_fare; } public void setCharged_fare(int charged_fare) { this.charged_fare = charged_fare; } public Date getBooking_travel_date() { return booking_travel_date; } public void setBooking_travel_date(Date booking_travel_date) { this.booking_travel_date = booking_travel_date; } public Date getBooking_time() { return booking_time; } public void setBooking_time(Date booking_time) { this.booking_time = booking_time; } public int getNum_seats_booked() { return num_seats_booked; } public void setNum_seats_booked(int num_seats_booked) { this.num_seats_booked = num_seats_booked; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getBus_id() { return bus_id; } public void setBus_id(int bus_id) { this.bus_id = bus_id; } public int getTrip_id() { return trip_id; } public void setTrip_id(int trip_id) { this.trip_id = trip_id; } // public String getBooking_travel_date_time() { // return booking_travel_date_time; // } // // public void setBooking_travel_date_time(String booking_travel_date_time) { // this.booking_travel_date_time = booking_travel_date_time; // } public Date getBooking_expirary_date() { return booking_expirary_date; } public void setBooking_expirary_date(Date booking_expirary_date) { this.booking_expirary_date = booking_expirary_date; } public boolean isMessage_sent_for_pickup() { return message_sent_for_pickup; } public void setMessage_sent_for_pickup(boolean message_sent_for_pickup) { this.message_sent_for_pickup = message_sent_for_pickup; } public boolean isMessage_sent_for_dropoff() { return message_sent_for_dropoff; } public void setMessage_sent_for_dropoff(boolean message_sent_for_dropoff) { this.message_sent_for_dropoff = message_sent_for_dropoff; } public Date getBooking_cancellation_date() { return booking_cancellation_date; } public void setBooking_cancellation_date(Date booking_cancellation_date) { this.booking_cancellation_date = booking_cancellation_date; } public Integer getCharged_free_rides() { return charged_free_rides; } public void setCharged_free_rides(Integer charged_free_rides) { this.charged_free_rides = charged_free_rides; } public String getCommuter_name() { return commuter_name; } public void setCommuter_name(String commuter_name) { this.commuter_name = commuter_name; } public String getFrom_stop_name() { return from_stop_name; } public void setFrom_stop_name(String from_stop_name) { this.from_stop_name = from_stop_name; } public String getTo_stop_name() { return to_stop_name; } public void setTo_stop_name(String to_stop_name) { this.to_stop_name = to_stop_name; } // public BookingWebDTO toBookingWebDTO(Booking b) { // this.id = b.getId(); // this.commuter_id = b.getCommuter_id(); // this.from_stop = b.getFrom_stop(); // this.to_stop = b.getTo_stop(); // this.actual_fare = b.getActual_fare(); // this.charged_fare = b.getCharged_fare(); // this.booking_travel_date = b.getBooking_travel_date(); // this.booking_time = b.getBooking_time(); // this.num_seats_booked = b.getNum_seats_booked(); // this.status = b.getStatus(); // this.bus_id = b.getBus_id(); // this.trip_id = b.getTrip_id(); // this.booking_travel_date_time = b.getBooking_travel_date_time(); // this.booking_expirary_date = b.getBooking_expirary_date(); // this.message_sent_for_pickup = b.isMessage_sent_for_pickup(); // this.message_sent_for_dropoff = b.isMessage_sent_for_dropoff(); // this.booking_cancellation_date = b.getBooking_cancellation_date(); // this.charged_free_rides = b.getCharged_free_rides(); // this.commuter_name = "test"; // this.from_stop_name = "pointa"; // this.to_stop_name = "pointb"; // return this; // } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } @Override public int compareTo(BookingWebDTO o) { return ((Integer)id).compareTo((Integer)o.id); } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getTrip_name() { return trip_name; } public void setTrip_name(String trip_name) { this.trip_name = trip_name; } public String getTrip_type() { return trip_type; } public void setTrip_type(String trip_type) { this.trip_type = trip_type; } @Override public String toString() { return "BookingWebDTO [id=" + id + ", commuter_id=" + commuter_id + ", from_stop=" + from_stop + ", to_stop=" + to_stop + ", actual_fare=" + actual_fare + ", charged_fare=" + charged_fare + ", booking_travel_date=" + booking_travel_date + ", booking_time=" + booking_time + ", num_seats_booked=" + num_seats_booked + ", status=" + status + ", bus_id=" + bus_id + ", trip_id=" + trip_id + ", booking_expirary_date=" + booking_expirary_date + ", message_sent_for_pickup=" + message_sent_for_pickup + ", message_sent_for_dropoff=" + message_sent_for_dropoff + ", booking_cancellation_date=" + booking_cancellation_date + ", charged_free_rides=" + charged_free_rides + ", commuter_name=" + commuter_name + ", mobile=" + mobile + ", gender=" + gender + ", from_stop_name=" + from_stop_name + ", to_stop_name=" + to_stop_name + ", trip_name=" + trip_name + ", trip_type=" + trip_type + "]"; } } <file_sep>package com.main.sts.entities; import com.main.sts.dto.StopsDTO; public class StopPosition { public StopsDTO stop; boolean user_boarding_point = false; boolean user_drop_off_point = false; boolean vehicle_started_point = false; // boolean vehicle_current_location = false; // // boolean user_current_location = false; public boolean isUser_boarding_point() { return user_boarding_point; } public void setUser_boarding_point(boolean user_boarding_point) { this.user_boarding_point = user_boarding_point; } public boolean isUser_drop_off_point() { return user_drop_off_point; } public void setUser_drop_off_point(boolean user_drop_off_point) { this.user_drop_off_point = user_drop_off_point; } public boolean isVehicle_started_point() { return vehicle_started_point; } public void setVehicle_started_point(boolean vehicle_started_point) { this.vehicle_started_point = vehicle_started_point; } public StopsDTO getStop() { return stop; } public void setStop(StopsDTO stop) { this.stop = stop; } } <file_sep>package com.main.sts.messageworkers; import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.log4j.Logger; import org.springframework.stereotype.Repository; import com.main.sts.entities.DashboardSettings; import com.main.sts.util.MD5PassEncryptionClass; @Repository public class MailSender { public static Logger logger = Logger.getLogger(MailSender.class); private MD5PassEncryptionClass passwordEncrypt = new MD5PassEncryptionClass(); Properties props = null; private static Session session = null; public static DashboardSettings dashboardSettings; public void setAuth() { try { props = new Properties(); // logger.info(dashboardSettings); String serverHost = dashboardSettings.getSmtp_server_host(); if (serverHost == null) { System.out.println("ERROR: serverHost is null, Can't send emails"); return; } props.put("mail.smtp.auth", "true"); //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", serverHost);// "smtp.gmail.com" props.put("mail.smtp.port", dashboardSettings.getSmtp_port());// "587" // props.put("mail.smtp.host", serverHost); // props.put("mail.smtp.socketFactory.port", dashboardSettings.getSmtp_port()); // props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // props.put("mail.smtp.auth", "true"); // props.put("mail.smtp.port", dashboardSettings.getSmtp_port()); // session = Session.getInstance(props, new javax.mail.Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication(dashboardSettings.getFrom_email(), passwordEncrypt // .DecryptText(dashboardSettings.getSmtp_password())); // } // }); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(dashboardSettings.getFrom_email(), passwordEncrypt .DecryptText(dashboardSettings.getSmtp_password())); } }); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } } public static void sendMail(Mail mail) { try { logger.info("Sending mail to [ " + mail.getSendTo() + " ] Message: [ " + mail.getMessage() + " ]"); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(dashboardSettings.getFrom_email())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getSendTo())); message.setSubject(mail.getSubject()); message.setContent(mail.getMessage(), "text/html"); Transport.send(message); // Thread.sleep(1000); logger.info("Mail sent"); } catch (Exception e) { logger.info("Failed to send mail"); logger.error(e.getMessage()); e.printStackTrace(); } } // send mail with attachmnt by sami public void sendMailThreadWithAttach(final String toAddress, final String subject, final String sendMesg, final Session session, final DashboardSettings adminPreferences, final File file, final File csvfile) { // System.out.println(adminPreferences); this.session = session; // this.toAddress1 = toAddress; // this.subject1 = subject; // this.sendMesg1 = sendMesg; this.dashboardSettings = adminPreferences; // try { // MyThreadPoolExecutor emailThreadPoolExecutor = new // MyThreadPoolExecutor(); // emailThreadPoolExecutor.runTask(new Runnable() { // public void run() { try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(dashboardSettings.getFrom_email())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress)); message.setSubject(subject); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(dashboardSettings.getFrom_email())); InternetAddress[] toAddresses = {new InternetAddress(toAddress)}; msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part // MimeBodyPart messageBodyPart = new MimeBodyPart(); // creates multi-part Multipart multipart = new MimeMultipart(); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<html><b>" + sendMesg + "</b></html>", "text/html"); // adds attachments MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(file.getAbsoluteFile()); multipart.addBodyPart(attachPart); multipart.addBodyPart(htmlPart); // csv attachment by sami only below code added MimeBodyPart csvattach = new MimeBodyPart(); csvattach.attachFile(csvfile.getAbsoluteFile()); multipart.addBodyPart(csvattach); // ended // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); csvfile.delete(); file.delete(); } catch (Exception ae) { // TODO Auto-generated catch block ae.printStackTrace(); } logger.info("sent mail to [ " + toAddress + " ] with report as an attachment [ " + subject + " ]"); } // }); // end public void sendMailWithAttachment(String toAddress, String subject, String sendMesg, File file, File csvfile) { // System.out.println(adminPreferences); logger.info(MailSender.class + "sendMail with attachment method"); try { // System.out.println("passowrd "+adminPreferences.getPassword()); // System.out.println("after dec "+passwordEncrypt.DecryptText(adminPreferences.getPassword())); // MyThreadPoolExecutor emailThreadPoolExecutor=new // MyThreadPoolExecutor(); sendMailThreadWithAttach(toAddress, subject, sendMesg, session, dashboardSettings, file, csvfile); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.main.sts; import javax.annotation.Resource; import org.junit.Assert; import org.junit.Test; import com.main.sts.dto.response.ReferralDTO; import com.main.sts.entities.ReferralCode; import com.main.sts.service.ReferralCodeService; public class ReferralCodeServiceTest extends BaseTest { @Resource private ReferralCodeService referralCodeService; @Test public void testGenerateReferralCode() { ReferralCode referralCode = referralCodeService.getOrGenerateReferralCode(1); Assert.assertNotNull(referralCode); for (ReferralCode c : referralCodeService.findAll()) { System.out.println(c.getId() + "--" + c.getCode() + "--" + c.getReferred_by()); } } @Test public void testGetReferralCode() { ReferralDTO referralCode = referralCodeService.getReferralCode(1); Assert.assertNotNull(referralCode); System.out.println(referralCode.getId() + "--" + referralCode.getCode() + "--" + referralCode.getReferral_message() + "--" + referralCode.getReferral_scheme_desc()); } @Test public void testFindAll() { Assert.assertFalse(referralCodeService.findAll().isEmpty()); for (ReferralCode c : referralCodeService.findAll()) { System.out.println(c.getId() + "--" + c.getCode() + "--" + c.getReferred_by()); } } } <file_sep>package com.main.sts.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; public class DateUtil { //private static TimeZone timezone = TimeZone.getTimeZone("IST"); private static DateFormat formatter = null; public static Date converStringToDateObject(String date) { Date new_date = null; try { formatter = new SimpleDateFormat(SystemConstants.DATE_FORMAT); new_date = formatter.parse(date); } catch (Exception e) { e.printStackTrace(); } return new_date; } public static Set<Date> dateInterval(Date initial, Date finall) { Set<Date> dates = new TreeSet<Date>(); Calendar calendar = Calendar.getInstance(); calendar.setTime(initial); while (calendar.getTime().before(finall) || calendar.getTime().equals(finall)) { Date result = calendar.getTime(); dates.add(result); calendar.add(Calendar.DATE, 1); } return dates; } public static Date getNewDate() { Calendar ISTTime = new GregorianCalendar(); return ISTTime.getTime(); } public static Calendar getCalendar() { Calendar cal = Calendar.getInstance(); return cal; } public static Date getTodayDateWithOnlyDate() { return getOnlyTodayDate(new Date()); } public static Date getOnlyTodayDate(Date date) { Calendar cal = getOnlyTodayDateCal(date); Date d = cal.getTime(); System.out.println("today date" + d); return d; } public static Calendar getOnlyTodayDateCal(Date date) { System.out.println("date:"+date); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 0); //cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); System.out.println("cal:"+cal.getTime()); return cal; } public static DateRange getStartAndEndOfTripDate(Date trip_date) { // Date today = date; // today.setHours(0); // today.setMinutes(0); // today.setSeconds(0); // 2015-11-19:00:00:00 Calendar cal = Calendar.getInstance(); cal.setTime(trip_date); cal.set(Calendar.HOUR_OF_DAY, 0); //cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); Date today = cal.getTime(); // 2015-11-20:00:00:00 Calendar c = Calendar.getInstance(); c.setTime(today); c.add(Calendar.DATE, 1); Date endOfDay = c.getTime(); System.out.println("today:" + today + "----tomorrow:" + endOfDay); return new DateRange(today, endOfDay); } public static void main(String[] args) { System.out.println(getNewDate()); System.out.println(getOnlyTodayDate(new Date())); System.out.println(getOnlyTodayDateCal(new Date()).getTime()); } public static class DateRange { private Date startDate; private Date endDate; public DateRange(Date startDate, Date endDate) { this.startDate = startDate; this.endDate = endDate; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } } } <file_sep>package com.main.sts.common; import com.main.sts.service.ReturnCodes; /** * Common Service exception. * * @author rahul * */ public class ServiceException extends Exception { public static enum ErrorType { ILLEGAL_ARGUMENT; } private ErrorType errorType; private ReturnCodes returnCode; public ServiceException() { super(); } public ServiceException(String message) { super(message); } public ServiceException(String message, ReturnCodes returnCode) { super(message); this.returnCode = returnCode; } public ServiceException(String message, ErrorType errorType, ReturnCodes returnCode) { super(message); this.errorType = errorType; this.returnCode = returnCode; } public ServiceException(String message, Throwable cause) { super(message, cause); } public ServiceException(String message, Throwable cause, ReturnCodes returnCode) { super(message, cause); this.returnCode = returnCode; } public ReturnCodes getReturnCode() { return returnCode; } public void setReturnCode(ReturnCodes returnCode) { this.returnCode = returnCode; } public ErrorType getErrorType() { return errorType; } public void setErrorType(ErrorType errorType) { this.errorType = errorType; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "sms_codes") public class SMSCode implements Comparable<SMSCode>, Serializable { @Id @GeneratedValue private int id; @Column(name = "user_id") private int commuter_id; private int code; private int status; private Timestamp created_at; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public Timestamp getCreated_at() { return created_at; } public void setCreated_at(Timestamp created_at) { this.created_at = created_at; } @Override public String toString() { return "SmsCodes [id=" + id + ", commuter_id=" + commuter_id + ", code=" + code + ", status=" + status + ", created_at=" + created_at + "]"; } @Override public int compareTo(SMSCode o) { return ((Integer) id).compareTo(o.getId()); } } <file_sep>package com.ec.eventserver.dao; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.ec.eventserver.models.DeviceInfo; import com.main.sts.dao.sql.BaseDao; @Repository public class DeviceDao extends BaseDao { public List<DeviceInfo> findAll() { return getAllRecords(DeviceInfo.class); } // it will return the ec_device_id as return value. public boolean insertADeviceInfo(DeviceInfo device_info) { device_info.setCreated_at(new Timestamp(new Date().getTime())); return insertEntity(device_info); } public boolean updateADeviceInfo(DeviceInfo device_info) { device_info.setUpdated_at(new Timestamp(new Date().getTime())); return updateEntity(device_info); } public boolean deleteDeviceInfo(DeviceInfo device_info) { return deleteEntity(device_info); } public DeviceInfo getDeviceInfoByECDeviceId(String ec_device_id) { // // order by created_at desc String query = "from DeviceInfo b where b.ec_device_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, ec_device_id); return getSingleRecord(DeviceInfo.class, query, parameters); } public DeviceInfo getDeviceInfoByHWDeviceId(String hw_device_id) { // // order by created_at desc String query = "from DeviceInfo b where b.hw_device_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, hw_device_id); return getSingleRecord(DeviceInfo.class, query, parameters); } public DeviceInfo getDeviceInfoByVehicleId(int vehicle_id) { // // order by created_at desc String query = "from DeviceInfo b where b.vehicle_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, vehicle_id); return getSingleRecord(DeviceInfo.class, query, parameters); } } <file_sep>package com.main.sts.entities; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "daily_driver_speed") public class DriverSpeedEntity { @Id @GeneratedValue private int id; private int driver_id; private String start_time; private String end_time; private String trip_name; private String bus_licence_number; private Date trip_running_date; private String driver_name; private Double start_longitude; private Double end_longitude; private Double start_latitude; private Double end_latitude; int highest_speed; public int getId() { return id; } public int getDriver_id() { return driver_id; } public String getStart_time() { return start_time; } public String getEnd_time() { return end_time; } public String getTrip_name() { return trip_name; } public String getBus_licence_number() { return bus_licence_number; } public Date getTrip_Running_Date() { return trip_running_date; } public String getDriver_name() { return driver_name; } public Double getStart_longitude() { return start_longitude; } public Double getEnd_longitude() { return end_longitude; } public Double getStart_latitude() { return start_latitude; } public Double getEnd_latitude() { return end_latitude; } public int getHighest_speed() { return highest_speed; } public void setId(int id) { this.id = id; } public void setDriver_id(int driver_id) { this.driver_id = driver_id; } public void setStart_time(String start_time) { this.start_time = start_time; } public void setEnd_time(String end_time) { this.end_time = end_time; } public void setTrip_name(String trip_name) { this.trip_name = trip_name; } public void setBus_licence_number(String bus_licence_number) { this.bus_licence_number = bus_licence_number; } public void setTrip_running_Date(Date date) { this.trip_running_date = date; } public void setDriver_name(String driver_name) { this.driver_name = driver_name; } public void setStart_longitude(Double start_longitude) { this.start_longitude = start_longitude; } public void setEnd_longitude(Double end_longitude) { this.end_longitude = end_longitude; } public void setStart_latitude(Double start_latitude) { this.start_latitude = start_latitude; } public void setEnd_latitude(Double end_latitude) { this.end_latitude = end_latitude; } public void setHighest_speed(int highest_speed) { this.highest_speed = highest_speed; } @Override public String toString() { return "DriverSpeedEntity [id=" + id + ", driver_id=" + driver_id + ", start_time=" + start_time + ", end_time=" + end_time + ", trip_name=" + trip_name + ", bus_licence_number=" + bus_licence_number + ", date=" + trip_running_date + ", driver_name=" + driver_name + ", start_longitude=" + start_longitude + ", end_longitude=" + end_longitude + ", stat_latitude=" + start_latitude + ", end_latitude=" + end_latitude + ", highest_speed=" + highest_speed + "]"; } } <file_sep>package com.main.sts.dto.response; import java.util.List; import com.main.sts.dto.AccountDTO; import com.main.sts.dto.FareDTO; public class PreBookingDetails { List<StopsResponseDTO> stops; FareDTO fare; AccountDTO account; public List<StopsResponseDTO> getStops() { return stops; } public void setStops(List<StopsResponseDTO> stops) { this.stops = stops; } public FareDTO getFare() { return fare; } public void setFare(FareDTO fare) { this.fare = fare; } public AccountDTO getAccount() { return account; } public void setAccount(AccountDTO account) { this.account = account; } @Override public String toString() { return "PreBookingDetails [stops=" + stops + ", fare=" + fare + "]"; } }<file_sep>package com.ec.eventserver.dto.request; import java.io.Serializable; public class DeviceRequest implements Serializable { String hw_device_id; public String getHw_device_id() { return hw_device_id; } public void setHw_device_id(String hw_device_id) { this.hw_device_id = hw_device_id; } } <file_sep>package com.main.sts.controllers.rest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.main.sts.common.ServiceException; import com.main.sts.common.ServiceException.ErrorType; import com.main.sts.dto.Response; import com.main.sts.dto.UserGPSDataDTO; import com.main.sts.dto.VehicleGPSDataDTO; import com.main.sts.entities.TrackingDetails; import com.main.sts.service.ReturnCodes; import com.main.sts.service.VehicleTrackingService; @Controller @RequestMapping("/vehicle_tracking") public class VehicleTrackingController { @Autowired private VehicleTrackingService vehicleTrackingService; static final Logger logger = Logger.getLogger(VehicleTrackingController.class); @RequestMapping(value = "/store_vehicle_pos", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> storeVehiclePos(@RequestBody VehicleGPSDataDTO dto) { ReturnCodes returnCode = ReturnCodes.UNKNOWN_ERROR; Response resp = new Response(); try { returnCode = vehicleTrackingService.storeVehiclePos(dto); if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_SUCCESS) { resp.message = "Insert success"; } else if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_FAILED) { resp.message = "Insert failed"; } // resp.response = dto; resp.returnCode = returnCode.name(); System.out.println(resp); System.out.println("--->>" + new ResponseEntity<Response>(resp, HttpStatus.OK)); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.returnCode = returnCode.name(); System.out.println(resp); return new ResponseEntity<Response>(resp, HttpStatus.OK); } } @RequestMapping(value = "/start_trip", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> startTrip(@RequestBody VehicleGPSDataDTO dto) { ReturnCodes returnCode = ReturnCodes.UNKNOWN_ERROR; Response resp = new Response(); try { returnCode = vehicleTrackingService.startTrip(dto); if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_SUCCESS) { resp.message = "Insert success"; } else if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_FAILED) { resp.message = "Insert failed"; } // resp.response = dto; resp.returnCode = returnCode.name(); System.out.println(resp); System.out.println("--->>" + new ResponseEntity<Response>(resp, HttpStatus.OK)); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.returnCode = returnCode.name(); System.out.println(resp); return new ResponseEntity<Response>(resp, HttpStatus.OK); } } @RequestMapping(value = "/end_trip", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> endTrip(@RequestBody VehicleGPSDataDTO dto) { ReturnCodes returnCode = ReturnCodes.UNKNOWN_ERROR; Response resp = new Response(); try { returnCode = vehicleTrackingService.endTrip(dto); if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_SUCCESS) { resp.message = "Insert success"; } else if (returnCode == ReturnCodes.VEHICLE_POS_INSERT_FAILED) { resp.message = "Insert failed"; } // resp.response = dto; resp.returnCode = returnCode.name(); System.out.println(resp); System.out.println("--->>" + new ResponseEntity<Response>(resp, HttpStatus.OK)); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.returnCode = returnCode.name(); System.out.println(resp); return new ResponseEntity<Response>(resp, HttpStatus.OK); } } @RequestMapping(value = "/trackByBookingId/{booking_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> trackByBookingId(@PathVariable Integer booking_id) { TrackingDetails trackingDetails = null; Response resp = new Response(); try { trackingDetails = vehicleTrackingService.trackVehcileByBooking(booking_id); if (trackingDetails != null) { resp.response = trackingDetails; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } else { resp.response = null; resp.message = "Stops list are null"; resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { e.printStackTrace(); if (e instanceof ServiceException) { ErrorType errorType = ((ServiceException) e).getErrorType(); if (errorType == ErrorType.ILLEGAL_ARGUMENT) { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(resp, HttpStatus.BAD_REQUEST); } else { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); } } return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } @RequestMapping(value = "/trackByBookingId1/{booking_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> trackByBookingId1(@PathVariable Integer booking_id) { TrackingDetails trackingDetails = null; Response resp = new Response(); try { trackingDetails = vehicleTrackingService.trackVehcileByBooking1(booking_id); if (trackingDetails != null) { resp.response = trackingDetails; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } else { resp.response = null; resp.message = "Stops list are null"; resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { e.printStackTrace(); if (e instanceof ServiceException) { ErrorType errorType = ((ServiceException) e).getErrorType(); if (errorType == ErrorType.ILLEGAL_ARGUMENT) { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(resp, HttpStatus.BAD_REQUEST); } else { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); } } return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>$(document).ready(function() { $("table tbody").empty(); $("#loading").show(); load(); setInterval(function() { $("table tbody").empty(); $("#loading").show(); load(); }, 30000); $("a").click(function(){ var note=$(this).attr("value"); if(note=="ontime" || note=="late" || note=="verylate" || note=="outofservice" ){ $.ajax({ type:"POST", url:"homepage/getNotifications", data:"status="+note, success:function(result){ // result=JSON.parse(result); //alert(result); var append=""; for(var i=0;i<result.length;i++){ var label; if(result[i].vehicle_status==1){ label="label-info"; } if(result[i].vehicle_status==2){ label="label-warning"; } if(result[i].vehicle_status==3){ label="label-danger"; } //sami if(result[i].vehicle_status==4){ label="label-info"; } //ended append=append+'<li class="hoverable"><div class="col1"><div class="content"><div class="content-col1">' +'<div class="label '+label+' "><i class="icon-bullhorn"></i></div></div><div class="content-col2">' +'<div class="desc">'+result[i].notification+'</div></div></div></li>'; ; } $("#notifications").empty().append(append); } }); } }); }); function load(){ $.ajax({ url:"homepage/getHomePageData", type:"POST", success:function(result){ //alert(result); result=$.trim(result); //alert(result); var forNone=result.split("---"); //alert(out); if(forNone[0]=="none"){ $("#no_services").show(); $("#loading").hide(); $("#buses_running_outofservice").empty().append(forNone[1]); $("#buses_running_ontime").empty().append(0); $("#buses_running_late").empty().append(0); $("#buses_running_verylate").empty().append(0); } else{ $("#no_services").hide(); //alert(forNone[0]); var sts=forNone[1].split(":"); $("#buses_running_outofservice").empty().append(sts[3]); $("#buses_running_ontime").empty().append(sts[0]); $("#buses_running_late").empty().append(sts[1]); $("#buses_running_verylate").empty().append(sts[2]); var json=JSON.parse(forNone[0]); $("table tbody").empty(); for(var i=0;i<json.length;i++){ //alert(json[i].bus_licence_number); // "my, tags are, in here".split(/[ ,]+/) /* var res="none"; if(json[i].arrived_time!="none") res = json[i].arrived_time.split(" ");*/ var data= '<tr>'+ '<td><a href="bus_id:'+json[i].vehicle_id+':'+json[i].trip_id+'">'+json[i].vehicle_licence_number+' </a></td>'+ '<td>'+json[i].current_stop+' </td>'+ '<td>'+json[i].arrived_time+'</td>'+ '<td>'+json[i].users_in_bus+'</td>'+ //alert(); '<td><a data-toggle="modal" href="driver_id:'+json[i].driver_id+":"+json[i].trip_id+":"+' #myModal1"> '+json[i].driver_name+' </a></td>'; if(json[i].vehicle_status==1){ data=data+'<td><span class="label label-success">On Time</span></td>'; } if(json[i].vehicle_status==2){ data=data+'<td><span class="label label-warning">Late</span></td>'; } if(json[i].vehicle_status==3){ data=data+'<td><span class="label label-danger">Very Late</span></td>'; } if(json[i].vehicle_status==4){ data=data+'<td><span class="label label-info">Out Of Service</span></td>'; } data=data+'<td><a href="map_id:'+json[i].bus_id+":"+json[i].trip_id+'"> <i class="icon-map-marker"></i>&nbsp;Map</a></td>'+ '</tr>'; //alert(out_data[12]); $("table tbody").append(data); $("#loading").hide(); $("table tbody a ").click(function(event){ event.preventDefault(); var data=$(this).attr("href").split(":"); //alert($(this).attr("href")); if(data[0]=="bus_id"){ //alert($(this).attr("href")); var a1=window.open('bus?bus_id='+data[1]+"&trip_id="+data[2], data[0],'height=' + 600 + ',width=' + 900+ ',resizable=no,scrollbars=yes,toolbar=no,menubar=no,location=no'); } else if(data[0]=="map_id"){ //alert(data[2]); var a2=window.open('single_map?route_id=none&trip_id='+data[2], data[0],'height=' + 600 + ',width=' + 900+ ',resizable=no,scrollbars=yes,toolbar=no,menubar=no,location=no'); } else if(data[0]=="driver_id"){ //alert(data); $("#board_time").text(""); $("#exit_time").text(""); var send=data[2].split("#"); //alert(send); $.ajax({ url:"homepage/getdriverinformation", type:"POST", data:"driver_id="+data[1]+"&trip_id="+data[2], success:function(result){ if(result=="none"){ $("#board_time").text("none"); $("#exit_time").text("none"); } else{ var data=result.split("+"); $("#board_time").text(data[0]); $("#exit_time").text(data[1]); } } }); } }); } } }, error:function(){ } }); } /*var data= '<tr>'+ '<td><a onclick=" openWindow()" href="#">'+o[i].bus_licence+' </a></td>'+ '<td>'+o[i].current_stop+' </td>'+ '<td>'+o[i].arrived_time+'</td>'+ '<td>'+o[i].no_of_students+'</td>'+ '<td>'+o[i].driver_name+'</td>'+ '<td><span class="label label-warning">Late</span></td>'+ '<td><a href="#"> <i class="icon-map-marker"></i>&nbsp;Map</a></td>'+ '</tr>';*/<file_sep>package com.main.sts.dto.response; import java.io.Serializable; import java.sql.Timestamp; import com.main.sts.service.ReturnCodes; public class TransactionResponse implements Serializable { private Integer transaction_id; private ReturnCodes returnCode; private Integer commuter_id; private Integer credits_available; private Integer free_rides_available; private Timestamp created_at; private String message; public Integer getTransaction_id() { return transaction_id; } public void setTransaction_id(Integer transaction_id) { this.transaction_id = transaction_id; } public ReturnCodes getReturnCode() { return returnCode; } public void setReturnCode(ReturnCodes returnCode) { this.returnCode = returnCode; } public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getCredits_available() { return credits_available; } public void setCredits_available(Integer credits_available) { this.credits_available = credits_available; } public Integer getFree_rides_available() { return free_rides_available; } public void setFree_rides_available(Integer free_rides_available) { this.free_rides_available = free_rides_available; } public Timestamp getCreated_at() { return created_at; } public void setCreated_at(Timestamp created_at) { this.created_at = created_at; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "TransactionResponse [transaction_id=" + transaction_id + ", returnCode=" + returnCode + ", commuter_id=" + commuter_id + ", credits_available=" + credits_available + ", created_at=" + created_at + ", message=" + message + "]"; } } <file_sep>package com.main.sts.dao.sql; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.SavedRoutes; @Repository public class SavedRoutesDao extends BaseDao { public List<SavedRoutes> getAllSavedRoutes() { String query = "from SavedRoutes"; return getRecords(SavedRoutes.class, query, null); } public List<SavedRoutes> getAllSavedRoutes(int commuter_id) { String query = "from SavedRoutes where commuter_id= ? order by created_at desc "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getRecords(SavedRoutes.class, query, parameters); } public SavedRoutes getSavedRouteForACommuter(int commuter_id, int from_stop_id, int to_stop_id, Integer pickup_time_hours, Integer pickup_time_min, Integer dropoff_time_hours, Integer dropoff_time_min) { String query = "from SavedRoutes as b where b.commuter_id=? " + " AND b.from_stop_id=? AND b.to_stop_id=? "; // + " AND b.pickup_time_hours=? AND b.pickup_time_min=? " // + " AND b.dropoff_time_hours=? AND b.dropoff_time_min=? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); parameters.put(1, from_stop_id); parameters.put(2, to_stop_id); /* parameters.put(3, pickup_time_hours); parameters.put(4, pickup_time_min); parameters.put(5, dropoff_time_hours); parameters.put(6, dropoff_time_min); */ return getSingleRecord(SavedRoutes.class, query, parameters); } public boolean saveARoute(SavedRoutes savedRoute) { savedRoute.setCreated_at(new Date()); return this.insertEntity(savedRoute); } } <file_sep>package com.main.sts.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.AddressDao; import com.main.sts.entities.Address; @Service public class AddressService { @Autowired private AddressDao addressDao; public void insertAddress(Address address) { addressDao.insertAddress(address); } public void updateAddress(Address address) { addressDao.updateAddress(address); } public Address getAddress(int subscriber_id, String subscriber_type) { return addressDao.getAddress(subscriber_id, subscriber_type); } } <file_sep>package com.ec.eventserver.service; import javax.annotation.Resource; import org.junit.Test; import com.ec.eventserver.models.DeviceInfo; import com.main.sts.BaseTest; public class DeviceServiceTest extends BaseTest { @Resource private DeviceService deviceService; @Test public void insertDeviceInfo() { DeviceInfo device_info = new DeviceInfo(); device_info.setHw_device_id("abcd"); DeviceInfo newDeviceInfo = deviceService.insertDeviceInfo(device_info); System.out.println(newDeviceInfo); } } <file_sep>package com.main.sts.dao.sql; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.BusFarePriceEntity; @Repository public class FareDao extends BaseDao { public List<BusFarePriceEntity> findAll() { return getAllRecords(BusFarePriceEntity.class); } public BusFarePriceEntity getFareById(int fare_id) { String queryStr = "from BusFarePriceEntity r where r.fare_id =?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, fare_id); return getSingleRecord(BusFarePriceEntity.class, queryStr, parameters, 1); } public void insertFare(BusFarePriceEntity e) { // if (e.getSource_stop_id() == e.getDest_stop_id()) { // throw new IllegalArgumentException("Source and dest stops cant be same"); // } e.setCreated_at(new Date()); this.insertEntity(e); } public void updateFare(BusFarePriceEntity e) { e.setUpdated_at(new Date()); this.updateEntity(e); } public void deleteFare(BusFarePriceEntity e) { this.deleteEntity(e); } public void deleteFare(int fare_id) { BusFarePriceEntity e = getFareById(fare_id); this.deleteFare(e); } public BusFarePriceEntity fetchFare(int source_stop_id, int dest_stop_id) { String query = "from BusFarePriceEntity b where b.source_stop_id=? AND b.dest_stop_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, source_stop_id); parameters.put(1, dest_stop_id); return getSingleRecord(BusFarePriceEntity.class, query, parameters, true); } // basically it check the presence of source_stop_id and dest_stop_id in // both columns and gives only the results those are having common due to // AND condition between columns. In some cases, where we have two entries // defined in db (due to mistakes), it will take only one. public BusFarePriceEntity fetchFareMatchAny(int source_stop_id, int dest_stop_id) { String query = "from BusFarePriceEntity b where b.source_stop_id in (?,?) AND b.dest_stop_id in (?,?) order by created_at desc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, source_stop_id); parameters.put(1, dest_stop_id); parameters.put(2, source_stop_id); parameters.put(3, dest_stop_id); return getSingleRecord(BusFarePriceEntity.class, query, parameters, 1); } // public BusFarePriceEntity fetchFroFare(int source_stop_id, int // dest_stop_id) { // return fetchToFare(source_stop_id, dest_stop_id); // } } <file_sep>package com.main.sts.controllers.webapp; import java.util.Enumeration; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.main.sts.dto.AccountDTO; import com.main.sts.dto.BookingDTO; import com.main.sts.dto.FareDTO; import com.main.sts.dto.PreBookingDTO; import com.main.sts.dto.Response; import com.main.sts.dto.ShuttleTimingsDTO; import com.main.sts.dto.StopsDTO; import com.main.sts.dto.TripDTO; import com.main.sts.dto.response.BookingCancellationResponse; import com.main.sts.dto.response.BookingHistoryResponse; import com.main.sts.dto.response.BookingResponse; import com.main.sts.dto.response.PreBookingCreditDetails; import com.main.sts.dto.response.PreBookingDetails; import com.main.sts.dto.response.StopsResponseDTO; import com.main.sts.entities.Booking; import com.main.sts.entities.Commuter; import com.main.sts.entities.Session; import com.main.sts.service.BookingService; import com.main.sts.service.ReturnCodes; import com.main.sts.service.StopsService; import com.main.sts.service.TripService; @Controller @RequestMapping("/webapp/booking") public class BookingWebAppController extends CommonController { @Autowired private TripService tripService; @Autowired private StopsWebAppController swc; @Autowired private BookingService bookingService; @Autowired private StopsService stopsService; @Autowired private TransactionWebAppController twc; static final Logger logger = Logger.getLogger(BookingWebAppController.class); @RequestMapping(value = "/my_bookings") public ModelAndView getBookingByCommuterId(ModelAndView model, HttpServletRequest request, HttpSession session) { List<BookingHistoryResponse> bookings = null; try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } Commuter commuter = getCommuter(request); int commuter_id = commuter.getCommuter_id(); bookings = bookingService.toBookingHisotry(bookingService.getBookingByCommuterId(commuter_id)); } catch (Exception e) { e.printStackTrace(); } model.addObject("bookings", bookings); model.setViewName("/webapp/my_bookings"); return model; } @RequestMapping(value = "/bookingPage") public ModelAndView showBookingPage(ModelAndView model, HttpServletRequest request) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } HttpSession session = super.getSession(request); session.removeAttribute("booking_id"); // StopsWebAppController swc = new StopsWebAppController(); List<StopsDTO> list = swc.getFromStops(); // String from_list = list.toString(); // System.out.println("List Stops Booking"+from_list); // model.addObject("from_list", from_list); model.addObject("from_list", list); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/book_now"); return model; } private ModelAndView redirectToBookNow(String error_message, RedirectAttributes redir){ redir.addFlashAttribute("error",error_message); return new ModelAndView("redirect:/webapp/booking/bookingPage"); } @RequestMapping(value = "/available_shuttles", method = RequestMethod.POST) public ModelAndView showAvailableShuttles(ModelAndView model, HttpServletRequest request, PreBookingDTO preBookingDTO, RedirectAttributes redir) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } Commuter commuter1= getCommuter(request); HttpSession session = super.getSession(request); System.out.println("session11:"+session); session.removeAttribute("booking_id"); System.out.println("session11:"+session); String from_stop = request.getParameter("from_stop_id"); String to_stop = request.getParameter("to_stop_id"); if (from_stop != null && (from_stop.equals("null")||from_stop.equals(""))) { return redirectToBookNow("Please Choose Pick Up Point!", redir); } if (to_stop != null && (to_stop.equals("null")||to_stop.equals(""))) { return redirectToBookNow("Please Choose Drop Off Point!", redir); } if (from_stop == null) { return redirectToBookNow("Please Choose Pick Up Point!", redir); } if (to_stop == null) { return redirectToBookNow("Please Choose Drop Off Point!", redir); } int num_seats_choosen = 1; String seats = request.getParameter("num_seats"); if (seats != null) { num_seats_choosen = Integer.parseInt(seats); } Commuter commuter = getCommuter(request); int commuter_id = commuter.getCommuter_id(); int from_stop_id = Integer.parseInt(from_stop); int to_stop_id = Integer.parseInt(to_stop); String from = stopsService.getStop(from_stop_id).getStop_name(); String to = stopsService.getStop(to_stop_id).getStop_name(); preBookingDTO.setCommuter_id(commuter_id); preBookingDTO.setFrom_stop_id(from_stop_id); preBookingDTO.setTo_stop_id(to_stop_id); preBookingDTO.setNum_seats_choosen(num_seats_choosen); session.setAttribute("preBookingDTO", preBookingDTO); List<ShuttleTimingsDTO> trips = null; trips = tripService.getTodayAndTomorrowTrips(from_stop_id, to_stop_id); model.addObject("from_stop", from); model.addObject("to_stop", to); model.addObject("num_seats_choosen", num_seats_choosen); model.addObject("trips", trips); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/available_shuttles"); return model; } @RequestMapping(value = "/pre_booking_details", method = RequestMethod.POST) public ModelAndView getPreBookingDetails(ModelAndView model, HttpServletRequest request, PreBookingDTO preBookingDTO) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } HttpSession session = super.getSession(request); session.removeAttribute("booking_id"); PreBookingDetails preBookingDetails = null; preBookingDTO = (PreBookingDTO) session.getAttribute("preBookingDTO"); int trip_id = Integer.parseInt(request.getParameter("trip_id")); preBookingDTO.setTrip_id(trip_id); session.setAttribute("preBooking", preBookingDTO); preBookingDetails = bookingService.getPreBookingDetails(preBookingDTO.getCommuter_id(), preBookingDTO.getNum_seats_choosen(), preBookingDTO.getTrip_id(), preBookingDTO.getFrom_stop_id(), preBookingDTO.getTo_stop_id()); model.addObject("preBookingDTO", preBookingDTO); model.addObject("preBookingDetails", preBookingDetails); model.addObject("status", "success"); } catch (Exception e) { e.printStackTrace(); model.addObject("status", "failure"); } model.setViewName("/webapp/prebooking_details"); return model; } @RequestMapping(value = "/bookNow", method = RequestMethod.GET) public ModelAndView bookNow(ModelAndView model, HttpServletRequest request, HttpSession session) { BookingResponse bookingResp = new BookingResponse(); try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } HttpSession session1 = super.getSession(request); if (session1.getAttribute("booking_id") != null) { return showBookingPage(model, request); } Commuter commuter = getCommuter(request); int commuter_id = commuter.getCommuter_id(); System.out.println("Commuter " + commuter_id); session = super.getSession(request); PreBookingDTO preBookingDTO = (PreBookingDTO) session.getAttribute("preBooking"); BookingDTO bookingDTO = new BookingDTO(); bookingDTO.setCommuter_id(preBookingDTO.getCommuter_id()); bookingDTO.setFrom_stop_id(preBookingDTO.getFrom_stop_id()); bookingDTO.setTo_stop_id(preBookingDTO.getTo_stop_id()); bookingDTO.setTrip_id(preBookingDTO.getTrip_id()); bookingDTO.setNum_seats_choosen(preBookingDTO.getNum_seats_choosen()); System.out.println("bookingDTO:" + bookingDTO); boolean bookingMsgToBeSent = bookingDTO.isSms_send_enabled(); bookingResp = bookingService.bookNow(bookingDTO, bookingMsgToBeSent); // Dont add the Return code, as that is already set in bookNow // method with various return codes. // bookingResp.setReturnCode(ReturnCodes.BOOKING_SUCCESSFUL); System.out.println("bookingResp" + bookingResp); if(bookingResp.getReturnCode() == ReturnCodes.BOOKING_NOT_ENOUGH_BALANCE) { model.addObject("status", "NOT_ENOUGH_BALANCE"); return twc.getMyWallet(model, session, request); } BookingHistoryResponse booking = bookingService.getBookingDetailsById(bookingResp.getBooking_id()); model.addObject("status", "success"); model.setViewName("/webapp/boarding_pass"); model.addObject("booking", booking); session.setAttribute("booking_id", booking.getBooking_id()); } catch (Exception e) { e.printStackTrace(); bookingResp.setReturnCode(ReturnCodes.BOOKING_FAILED); model.addObject("status", "failure"); model.setViewName("/webapp/booking_information"); } return model; } @RequestMapping(value = "/boarding_pass", method=RequestMethod.POST) public ModelAndView showBoardingPass(ModelAndView model, HttpServletRequest request) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } BookingHistoryResponse booking = null; int booking_id = 0; String bookingId = request.getParameter("booking_id"); if (bookingId != null && bookingId != "") { booking_id = Integer.parseInt(bookingId); } booking = bookingService.getBookingDetailsById(booking_id); System.out.println("Boarding Pass "+booking); model.addObject("booking", booking); HttpSession session = super.getSession(request); session.setAttribute("booking_id", booking_id); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/boarding_pass"); return model; } @RequestMapping(value = "/cancelBooking", method = RequestMethod.POST) public ModelAndView cancelRide(ModelAndView model, HttpServletRequest request) { BookingCancellationResponse bookingCancellationResp = new BookingCancellationResponse(); try { int booking_id = Integer.parseInt(request.getParameter("booking_id")); bookingCancellationResp = bookingService.cancelRide(booking_id); if (bookingCancellationResp.getReturnCode() == null) { bookingCancellationResp.setReturnCode(ReturnCodes.BOOKING_CANCELLATION_SUCCESSFUL); } model.addObject("status", "booking_cancelled"); model.addObject("bookingCancellationResp", bookingCancellationResp); } catch (Exception e) { e.printStackTrace(); model.addObject("status", "booking_cancellation_failed"); } model.setViewName("/webapp/booking_information"); return model; } }<file_sep>package com.main.sts.entities; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Entity; @Entity @Table(name = "user_roles") public class Users_Roles { @Id private int user_id; private int role_id; public int getUser_id() { return user_id; } public int getRole_id() { return role_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public void setRole_id(int role_id) { this.role_id = role_id; } @Override public String toString() { return "Users_Roles [user_id=" + user_id + ", role_id=" + role_id + "]"; } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.RfidCards; import com.main.sts.service.RfidCardsService; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/rfid") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") /* * @PreAuthorize("isAuthenticated()") * * @Secured("ROLE_ADMIN") */ public class StaffRfidController { private static final Logger logger = Logger.getLogger(StudentRfidController.class); private static final String type = "staff"; @Autowired private RolesUtility rolesUtility; @Autowired private RfidCardsService rfidCardsService; @RequestMapping(value = "/staff", method = RequestMethod.GET) public ModelAndView seniorHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/rfid/staff_rfid_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "staff_rfid_list"); List<RfidCards> cards = rfidCardsService.getRfidsByType(type); model.addObject("staff_rfid_list", cards); // //System.out.println(rfidDaoImpl.getRfidListByType("student")); model.addObject("login_role", rolesUtility.getRole(request)); // System.out.println("inside staffRFID controller"); return model; } @RequestMapping(value = "/staff/add", method = RequestMethod.POST) public @ResponseBody String studentRfidAdd(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); /* * Sql database -- start */ boolean cardfound = rfidCardsService.rfidExists(rfid_number); if (cardfound == true) { return "rfid_exists"; } else { rfidCardsService.addRfid(rfid_number, type); logger.info("New Rfid number [ " + rfid_number + " ] has been registered with type Staff"); return "rfid_inserted"; } } @RequestMapping(value = "/staff/update", method = RequestMethod.POST) public @ResponseBody String studentRfidUpdate(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String current_rfid = request.getParameter("current_rfid"); String new_rfid = request.getParameter("new_rfid"); // //System.out.println("Current rfid="+current_rfid+" new rfid="+new_rfid); boolean reply = rfidCardsService.updateRfid(current_rfid, new_rfid); if (reply == true) { logger.info("Rfid number [ " + current_rfid + " ] changed to [ " + new_rfid + " ] type Staff"); return "rfid_inserted"; } else if (reply == false) { return "rfid_exists"; } else { return "rfid_notinserted"; } } @RequestMapping(value = "/staff/delete", method = RequestMethod.POST) public @ResponseBody String studentRfidDelete(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); boolean reply = rfidCardsService.deleteRfid(rfid_number); if (reply == true) { logger.info("Rfid number [ " + rfid_number + " ] type Student has been deleted"); return "rfid_deleted"; } else { return "rfid_notdeleted"; } } // search RFID starts @RequestMapping(value = "/staff/search", method = RequestMethod.POST) public @ResponseBody String searchRfid(HttpServletRequest request, Model model, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); List<RfidCards> rfids = rfidCardsService.searchRfids(rfid_number, type); session.setAttribute("rfids", rfids); return "/sts/school_admin/rfid/staffSearch"; } @RequestMapping(value = "/staffSearch", method = RequestMethod.GET) public ModelAndView staffSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/rfid/staff_rfid_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "staff_rfid_list"); List<RfidCards> rfids = (List<RfidCards>) session.getAttribute("rfids"); model.addObject("staff_rfid_list", rfids); // //System.out.println(rfids); if (rfids.isEmpty()) { // //System.out.println("null"); model.addObject("staff_rfid_list", rfidCardsService.getRfidsByType(type)); model.addObject("error_message", "noMatching"); } return model; } // search RFID ends @RequestMapping(value = "/removeAllStaffRFIDSByTripIds", method = RequestMethod.POST) public @ResponseBody String removeAllTripsByTripIds(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfids = request.getParameter("rfids"); // //System.out.println(rfids); String rfidsArray[] = rfids.split(","); int totalItems = rfidsArray.length; // //System.out.println(totalItems); for (int i = 1; i <= totalItems; i++) { // System.out.println("delete "+rfidsArray[i-1]); rfidCardsService.deleteRfid(rfidsArray[i - 1]); RfidCards rfidCard = rfidCardsService.getRfidCard(rfidsArray[i - 1]); rfidCardsService.deleteRfid(rfidCard); logger.info("Rfid [ " + rfidCard.getRfid_number() + " ] deleted from [ " + rfidCard.getType() + " ] cards list"); } return "staff"; } } <file_sep>package com.main.sts; import java.util.List; import java.util.Set; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.service.RouteStopsService; public class RouteStopServiceTest extends BaseTest { @Resource private RouteStopsService routeStopService; @Test public void testFindAll() { Assert.assertFalse(routeStopService.findAll().isEmpty()); for (Stops c : routeStopService.findAll()) { System.out.println(c.getStop_name()); } } @Test public void testFindAllAvailableFromStops() { Set<RouteStops> routeStops = routeStopService.getAllAvailableFromStops(); for (RouteStops rs : routeStops) { System.out.println(rs.getId() + "--" +rs.getStop_id() + "--" + rs.getStop_number() + "--" + rs.getStop().getStop_name()); } } @Test public void testFindAllAvailableToStops() { int stop_id = 741; stop_id=33; List<RouteStops> routeStops = routeStopService.getAllAvailableToStops(stop_id); for (RouteStops rs : routeStops) { System.out.println(rs.getId() + "--" + rs.getStop_number() + "--" + rs.getStop().getStop_name()); } } @Test public void testFindAllAvailableFromAndToStops() { Set<RouteStops> routeFromStops = routeStopService.getAllAvailableFromStops(); for (RouteStops rs : routeFromStops) { System.out.println(rs.getId() + "--" + rs.getStop_number() + "--" + rs.getStop().getStop_name()); System.out.print("-------------"); List<RouteStops> routeToStops = routeStopService.getAllAvailableToStops(rs.getStop_id()); for (RouteStops rs1 : routeToStops) { System.out.println("\t\t"+rs1.getId() +" "+rs1.getStop_id() + "--" + rs1.getStop_number() + "--" + rs1.getStop().getStop_name()); } } } @Test public void testFindAllAvailableFromAndToStops1() { Set<RouteStops> routeFromStops = routeStopService.getAllAvailableFromStops(); for (RouteStops rs : routeFromStops) { System.out.println(rs.getId() + "--" + rs.getStop_number() + "--" + rs.getStop().getStop_name()); System.out.print("-------------"); } List<RouteStops> routeToStops = routeStopService.getAllAvailableToStops(34); for (RouteStops rs1 : routeToStops) { System.out.println("\t\t"+rs1.getId() +" "+rs1.getStop_id() + "--" + rs1.getStop_number() + "--" + rs1.getStop().getStop_name()); } } } <file_sep>package com.main.sts.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.BusesDao; import com.main.sts.entities.Buses; @Service public class BusesService { @Autowired private BusesDao busesDao; public List<Buses> getBuses() { return busesDao.getAllrecords(); } public Buses getBusByLicence(String bus_licence_number) { return busesDao.getBus(bus_licence_number); } public void insertBus(Buses busEntity) { busEntity.setBus_allotted(0); busesDao.insertBus(busEntity); } public Buses getBusById(int bus_id) { return busesDao.getBusById(bus_id); } public void updateBus(Buses busEntity) { // busEntity.setBus_allotted(busEntity.getBus_allotted()); busesDao.updateBus(busEntity); } public void deleteBus(int busId) { Buses bus = getBusById(busId); busesDao.deleteBus(bus); } public void updateBusStatus(Buses busEntity, int status) { busEntity.setBus_allotted(status); busesDao.updateBus(busEntity); } public List<Buses> searchBuses(String type, String str) { return busesDao.searchBuses(str, type); } public Buses getBusByDriverId(int id) { String queryStr = "from Buses b where b.driverId=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return busesDao.getSingleRecord(Buses.class, queryStr, parameters); } } <file_sep>package com.main.sts.dto.response; public class BookingStopDetailsResponse { String stop_image_path; String help_text; // e.g. EXPIRED String booking_status; public String getStop_image_path() { return stop_image_path; } public void setStop_image_path(String stop_image_path) { this.stop_image_path = stop_image_path; } public String getHelp_text() { return help_text; } public void setHelp_text(String help_text) { this.help_text = help_text; } public String getBooking_status() { return booking_status; } public void setBooking_status(String booking_status) { this.booking_status = booking_status; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; import com.main.sts.common.CommonConstants; @Entity @Table(name = "booking") /** * @author rahul * */ public class Booking implements Comparable<Booking>, Serializable { // //@SequenceGenerator(name = "booking_id_seq_gen", sequenceName = "booking_id_seq") // @Id // @GenericGenerator(name = "sequence", strategy = "sequence", parameters = { // @org.hibernate.annotations.Parameter(name = "sequenceName", value = "sequence"), // @org.hibernate.annotations.Parameter(name = "allocationSize", value = "1"), // }) // @GeneratedValue(generator = "sequence", strategy=GenerationType.SEQUENCE) // @Id // @GenericGenerator(name = "booking_id_seq_gen", strategy = "sequence", parameters = { // @org.hibernate.annotations.Parameter(name = "sequenceName", value = "booking_id_seq"), // @org.hibernate.annotations.Parameter(name = "allocationSize", value = "1"),}) //@GeneratedValue(generator = "booking_id_seq_gen", strategy = GenerationType.IDENTITY) // @GeneratedValue(strategy = GenerationType.IDENTITY) // @Id // @GenericGenerator(name = "booking_id_seq_gen", strategy = "enhanced-table", parameters = { // @org.hibernate.annotations.Parameter(name = "table_name", value = "sequence_table") // }) // @GeneratedValue(generator = "table", strategy=GenerationType.TABLE) // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "booking_id_seq_gen") @SequenceGenerator(name = "booking_id_seq_gen", sequenceName = "booking_id_seq") private int id; private int commuter_id; private int from_stop; private int to_stop; private int actual_fare; private int charged_fare; private Date booking_travel_date; private Date booking_time; private int num_seats_booked = 1; /** * {@link CommonConstants.BookingStatus#getBookingStatus()} */ // Use BookingStatus.getBookingStatus for dealing with this variable. // don't hardcode the value anywhere in code. use this enum. private int status; private int bus_id; private int trip_id; @Transient private String booking_travel_date_time; private Date booking_expirary_date; private boolean message_sent_for_pickup; private boolean message_sent_for_dropoff; private Date booking_cancellation_date; // if a user try to book 4 person in one ticket, we will deduct 4 free rides. private Integer charged_free_rides; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public int getFrom_stop() { return from_stop; } public void setFrom_stop(int from_stop) { this.from_stop = from_stop; } public int getTo_stop() { return to_stop; } public void setTo_stop(int to_stop) { this.to_stop = to_stop; } public int getActual_fare() { return actual_fare; } public void setActual_fare(int actual_fare) { this.actual_fare = actual_fare; } public int getCharged_fare() { return charged_fare; } public void setCharged_fare(int charged_fare) { this.charged_fare = charged_fare; } public Date getBooking_travel_date() { return booking_travel_date; } public void setBooking_travel_date(Date booking_travel_date) { this.booking_travel_date = booking_travel_date; } public Date getBooking_time() { return booking_time; } public void setBooking_time(Date booking_time) { this.booking_time = booking_time; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getBus_id() { return bus_id; } public void setBus_id(int bus_id) { this.bus_id = bus_id; } public int getTrip_id() { return trip_id; } public void setTrip_id(int trip_id) { this.trip_id = trip_id; } public int getNum_seats_booked() { return num_seats_booked; } public void setNum_seats_booked(int num_seats_booked) { this.num_seats_booked = num_seats_booked; } public String getBooking_travel_date_time() { SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm"); System.out.println("booking_travel_date:"+booking_travel_date); Date d = booking_travel_date; if (d != null) { String text = sdf.format(d); booking_travel_date_time = text; } return booking_travel_date_time; } public String[] getBookingTravelDateAndTimeString() { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd-MM-yyyy"); SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm a"); System.out.println("booking_travel_date:" + booking_travel_date); Date d = booking_travel_date; String[] dateTime = new String[2]; if (d != null) { String date = dateFormat.format(d); String time = timeFormat.format(d); dateTime[0] = date; dateTime[1] = time; return dateTime; } return null; } // public void setBooking_travel_date_time(String booking_travel_date_time) { // this.booking_travel_date_time = booking_travel_date_time; // } @Override public int compareTo(Booking o) { return ((Integer) o.getId()).compareTo((Integer) o.getId()); } public Date getBooking_expirary_date() { return booking_expirary_date; } public void setBooking_expirary_date(Date booking_expirary_date) { this.booking_expirary_date = booking_expirary_date; } public boolean isMessage_sent_for_pickup() { return message_sent_for_pickup; } public void setMessage_sent_for_pickup(boolean message_sent_for_pickup) { this.message_sent_for_pickup = message_sent_for_pickup; } public boolean isMessage_sent_for_dropoff() { return message_sent_for_dropoff; } public void setMessage_sent_for_dropoff(boolean message_sent_for_dropoff) { this.message_sent_for_dropoff = message_sent_for_dropoff; } public Date getBooking_cancellation_date() { return booking_cancellation_date; } public void setBooking_cancellation_date(Date booking_cancellation_date) { this.booking_cancellation_date = booking_cancellation_date; } public void setBooking_travel_date_time(String booking_travel_date_time) { this.booking_travel_date_time = booking_travel_date_time; } public Integer getCharged_free_rides() { if (charged_free_rides == null) { charged_free_rides = 0; } return charged_free_rides; } public void setCharged_free_rides(Integer charged_free_rides) { this.charged_free_rides = charged_free_rides; } @Override public String toString() { return "Booking [id=" + id + ", commuter_id=" + commuter_id + ", from_stop=" + from_stop + ", to_stop=" + to_stop + ", actual_fare=" + actual_fare + ", charged_fare=" + charged_fare + ", booking_travel_date=" + booking_travel_date + ", booking_time=" + booking_time + ", num_seats_booked=" + num_seats_booked + ", status=" + status + ", bus_id=" + bus_id + ", trip_id=" + trip_id + ", booking_travel_date_time=" + booking_travel_date_time + ", booking_expirary_date=" + booking_expirary_date + ", message_sent_for_pickup=" + message_sent_for_pickup + ", message_sent_for_dropoff=" + message_sent_for_dropoff + ", booking_cancellation_date=" + booking_cancellation_date + "]"; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Transport; @Repository public class TransportDao extends BaseDao { public Transport getTransport(int subscriber_id, String subscriber_type, String transport_type) { String queryStr = "from Transport b where b.subscriber_id=? and b.subscriber_type=? and b.transport_type=? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, subscriber_id); parameters.put(1, subscriber_type); parameters.put(2, transport_type); return getSingleRecord(Transport.class, queryStr, parameters); } public List<Transport> getSubscriberId(int trip_id, String s) { String auery = "from Transport b where b.subscriber_type=? and trip_id=?"; Map<Integer, Object> param = new HashMap<Integer, Object>(); param.put(0, s); param.put(1, trip_id); return getRecords(Transport.class, auery, param); } } <file_sep>package com.main.sts.service; import java.util.Date; import javax.annotation.Resource; import org.junit.Test; import com.main.sts.BaseTest; import com.main.sts.entities.PaymentTransaction; public class PaymentTransactionServiceTest extends BaseTest { @Resource private PaymentTransactionService paymentTxService; @Test public void insertPaymentTransaction() { PaymentTransaction paymentTx = new PaymentTransaction(); paymentTx.commuter_id = 80; paymentTx.mihpayid = "403993715513773344"; paymentTx.mode = "CC"; paymentTx.txnid = "3ac6706bbcc27316a498"; paymentTx.amount = 10.0; paymentTx.email = "<EMAIL>%4<EMAIL>"; paymentTx.mobile = "9494740413"; paymentTx.status = "success"; paymentTx.bank_ref_num = "830790561053161"; paymentTx.bankcode = "CC"; paymentTx.error = "E000"; paymentTx.error_message = "No+Error"; paymentTx.discount = 0.00; paymentTx.net_amount_debit = 10; int id = paymentTxService.insertUserPaymentDetails(paymentTx); System.out.println("id:" + id); } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.AdminEmails; @Repository public class AdminEmailDao extends BaseDao{ public List<AdminEmails> getAllMails(){ return (List<AdminEmails>) getAllRecords(AdminEmails.class); } public void addEmail(AdminEmails adminEmails){ insertEntity(adminEmails); } public void deleteEmail(AdminEmails adminEmails){ deleteEntity(adminEmails); } public AdminEmails getSingleMail(Integer id){ String queryStr = "from AdminEmails d where d.id = ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return getSingleRecord(AdminEmails.class, queryStr, parameters); } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.gson.Gson; import com.main.sts.entities.Buses; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Routes; import com.main.sts.entities.TripDetail; import com.main.sts.service.BusesService; import com.main.sts.service.RouteService; import com.main.sts.service.RouteStopsService; import com.main.sts.service.TripDetailService; import com.main.sts.util.ErrorCodes; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/trip") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") /* * @PreAuthorize("isAuthenticated()") * * @Secured("ROLE_ADMIN") */ public class TripsDetailsControllers { private static final Logger logger = Logger.getLogger(TripsDetailsControllers.class); @Autowired private RolesUtility rolesUtility; // PLEASE NOTE: DONT DEFINE ANY TRIPSERVICE In THIS CLASS. AS THAT WILL // BREAK THINGS. @Autowired private TripDetailService tripDetailService; @Autowired private BusesService busservice; @Autowired private RouteService routeservice; @Autowired private RouteStopsService routestopservice; @RequestMapping(value = "/trips", method = RequestMethod.GET) public ModelAndView tripssHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // System.out.println("inside trips controller:"); // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/trip/trips_list"); DateFormat formatter = new SimpleDateFormat("dd-MMy-yyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); List<TripDetail> tripDetails = tripDetailService.getAllTripDetails(); Collections.sort(tripDetails); model.addObject("trips", tripDetails); model.addObject("current_page", "trips"); // //System.out.println("inside tripcontroller"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } // search trips @RequestMapping(value = "/trip/search", method = RequestMethod.POST) public @ResponseBody String searchStudent(HttpServletRequest request, Model model, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); String searchOption = request.getParameter("searchOption"); System.out.println("inside controller" + rfid_number + " " + searchOption); List<TripDetail> searchtrips = new ArrayList<TripDetail>(); if (searchOption.equals("trip_name")) { searchtrips = tripDetailService.searchTripDetails(searchOption, rfid_number); } else if (searchOption.equals("trip_type")) { searchtrips = tripDetailService.searchTripDetails(searchOption, rfid_number); } else if (searchOption.equals("routeid")) { List<Routes> routes = routeservice.searchRoutes("route_name", rfid_number); for (Routes routes2 : routes) { TripDetail tripDetail = tripDetailService.getTripRouteIdOrBusId(routes2.getId(), 0); searchtrips.add(tripDetail); } } else if (searchOption.equals("busid")) { List<Buses> routes = busservice.searchBuses("bus_licence_number", rfid_number); for (Buses routes2 : routes) { TripDetail tripDetail = tripDetailService.getTripRouteIdOrBusId(routes2.getBus_id(), 1); searchtrips.add(tripDetail); } } session.setAttribute("searchtrips", searchtrips); return "/sts/school_admin/trip/tripSearch"; } @RequestMapping(value = "/tripSearch", method = RequestMethod.GET) public ModelAndView studentSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/trip/trips_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "students"); @SuppressWarnings("unchecked") List<TripDetail> searchStudentsList = (List<TripDetail>) session.getAttribute("searchtrips"); model.addObject("trips", searchStudentsList); // System.out.println(searchStudentsList); if (searchStudentsList == null || searchStudentsList.isEmpty()) { // System.out.println("trips empty"); model.addObject("trips", tripDetailService.getAllTrips()); model.addObject("error_message", "noMatching"); } model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/addTrip", method = RequestMethod.GET) public ModelAndView addStop(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/trip/addtrip"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); // get all buses model.addObject("buses", busservice.getBuses()); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/addtripaction", method = RequestMethod.GET) public String addRouteAction(final Model model, HttpServletRequest request, @ModelAttribute("trip") TripDetail tripDetails, HttpSession session) throws ParseException { // System.out.println("inside addtripaction controller"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { // System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } System.out.println(request.getParameter("route_name") + " " + request.getParameter("bus_id")); String bus_id = request.getParameter("bus_id"); Buses busEntity = busservice.getBusByLicence(bus_id); String fs = (String) session.getAttribute("fs"); String ls = (String) session.getAttribute("ls"); model.addAttribute("login_role", rolesUtility.getRole(request)); // validation for stop name duplicate starts TripDetail tripEntity = tripDetailService.getTripDetailsByName(tripDetails.getTrip_name()); String arr = request.getParameter("route_name"); String a[] = arr.split(";;"); int routeId = Integer.parseInt(a[0]); // //System.out.println(busEntity); // trip.setTotal_seats(busEntity.getBus_capacity()); // trip.setSeats_filled(0); tripDetails.setBusid(busEntity.getBus_id()); tripDetails.setRouteid(routeId); tripDetails.setBus(busEntity); tripDetails.setRoutes(routeservice.getRoute(routeId)); if (tripEntity != null) { // System.out.println("tripEntity"+tripEntity); model.addAttribute("trip", tripDetails); model.addAttribute("error_message", "tripDup"); model.addAttribute("errorOccured", "yes"); model.addAttribute("fs", fs); model.addAttribute("ls", ls); model.addAttribute("buses", busservice.getBuses()); return "/school_admin/trip/addtrip"; } // validation for stop timings int tripStartTime = tripDetails.getTrip_start_time_hours() * 60 + tripDetails.getTrip_start_time_minutes(); int tripEndTime = tripDetails.getTrip_end_time_hours() * 60 + tripDetails.getTrip_end_time_minutes(); List<TripDetail> tripsDetail = tripDetailService.getTripDetailByBusId(busEntity.getBus_id()); logger.info("trips " + tripsDetail); for (TripDetail tripSingle : tripsDetail) { int triptripSingleStartTime = tripSingle.getTrip_start_time_hours() * 60 + tripSingle.getTrip_start_time_minutes(); int triptripSingleEndTime = tripSingle.getTrip_end_time_hours() * 60 + tripSingle.getTrip_end_time_minutes(); // TODO: for now disabling this // if (tripStartTime >= triptripSingleStartTime && tripStartTime <= triptripSingleEndTime) { // System.out.println("tripEntity" + tripDetails); // model.addAttribute("trip", tripDetails); // model.addAttribute("error_message", "tripStartTime"); // model.addAttribute("errorOccured", "yes"); // model.addAttribute("fs", fs); // model.addAttribute("ls", ls); // model.addAttribute("buses", busservice.getBuses()); // return "/school_admin/trip/addtrip"; // } // TODO: for now disabling this // if (tripEndTime >= triptripSingleStartTime && tripEndTime <= triptripSingleEndTime) { // // System.out.println("tripEntity"+tripEntity); // model.addAttribute("trip", tripDetails); // model.addAttribute("error_message", "tripEndTime"); // model.addAttribute("errorOccured", "yes"); // model.addAttribute("fs", fs); // model.addAttribute("ls", ls); // model.addAttribute("buses", busservice.getBuses()); // return "/school_admin/trip/addtrip"; // // } // TODO: for now disabling this // if (tripStartTime < triptripSingleStartTime && tripEndTime > triptripSingleEndTime) { // // System.out.println("tripEntity"+tripEntity); // model.addAttribute("trip", tripDetails); // model.addAttribute("error_message", "prevTrip"); // model.addAttribute("errorOccured", "yes"); // model.addAttribute("fs", fs); // model.addAttribute("ls", ls); // model.addAttribute("buses", busservice.getBuses()); // return "/school_admin/trip/addtrip"; // // } } /* * String strtTime[] = firstStopTimings.split(":"); int startStopHours = * Integer.parseInt(strtTime[0]); int startStopMinutes = * Integer.parseInt(strtTime[1]); int totalStartStopTime = * startStopHours * 60 + startStopMinutes; * * String secndTime[] = secondStopTimings.split(":"); int endStopHours = * Integer.parseInt(secndTime[0]); int endStopMinutes = * Integer.parseInt(secndTime[1]); int totalEndStopTime = endStopHours * * 60 + endStopMinutes; */ /* * if (tripStartTime >= totalStartStopTime) { * * model.addAttribute("trip", tripDetails); * model.addAttribute("error_message", "StartTripError"); * model.addAttribute("errorOccured", "yes"); model.addAttribute("fs", * fs); model.addAttribute("buses", busservice.getBuses()); * model.addAttribute("ls", ls); return "/school_admin/trip/addtrip"; } * * if (tripEndTime <= totalEndStopTime) { * System.out.println("tripEntity" + tripDetails); * model.addAttribute("trip", tripDetails); * model.addAttribute("error_message", "EndTripError"); * model.addAttribute("errorOccured", "yes"); model.addAttribute("fs", * fs); model.addAttribute("ls", ls); model.addAttribute("buses", * busservice.getBuses()); return "/school_admin/trip/addtrip"; } */ /* * school start time should be in between trip start time and stop1 * timings */ /* * int schoolHours = tripDetails.getSchool_time_hours(); int * schoolMinutes = tripDetails.getSchool_time_minutes(); int * schoolTotalMinutes = schoolHours * 60 + schoolMinutes; * * if (tripDetails.getTrip_type().equals("Pick Up")) { // * System.out.println("inside pick up"); * * if (schoolTotalMinutes <= totalEndStopTime || schoolTotalMinutes >= * tripEndTime) { // System.out.println("tripEntity"+trip); * model.addAttribute("trip", tripDetails); * model.addAttribute("error_message", "schoolArrivalTimeError"); * model.addAttribute("errorOccured", "yes"); // * System.out.println("saterror:"+trip.getRoutes().getRoute_name()); * model.addAttribute("fs", fs); model.addAttribute("ls", ls); * model.addAttribute("routes", routeservice.getAllRoutes()); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/addtrip"; } } * * if (tripDetails.getTrip_type().equals("Drop Off")) { // * System.out.println("inside Drop Off"); if (schoolTotalMinutes <= * tripStartTime || schoolTotalMinutes >= totalStartStopTime) { // * System.out.println("tripEntity"+trip); model.addAttribute("trip", * tripDetails); model.addAttribute("error_message", * "schoolStartTimeError"); model.addAttribute("errorOccured", "yes"); * model.addAttribute("fs", fs); model.addAttribute("ls", ls); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/addtrip"; } * * } */ try { tripDetailService.insertTripDetail(tripDetails); logger.info("New trip [" + tripDetails.getTrip_name() + " ] got added"); } catch (Exception e) { e.printStackTrace(); } // if route is assigned to a trip then it should not be deleted. String status = routeservice.getRoute(routeId).getIsAssigned(); int i = Integer.parseInt(status); routeservice.updateStatus(routeId, String.valueOf(++i)); int bs = busEntity.getBus_allotted(); busservice.updateBusStatus(busEntity, ++bs); return "redirect:/school_admin/trip/trips"; } @RequestMapping(value = "/updateTrip", method = RequestMethod.GET) public ModelAndView updateTrip(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); int trip_detail_id = Integer.parseInt(request.getParameter("id")); TripDetail tripDetail = tripDetailService.getTripDetail(trip_detail_id); int routeIdOld = tripDetail.getRoutes().getId(); // String routeNameOld=trip.getRoute_name(); model.addObject("trip", tripDetail); // System.out.println("%%%%%%%%%%%%%%"+trip); model.setViewName("/school_admin/trip/updatetrip"); // get all buses model.addObject("buses", busservice.getBuses()); // model.addObject("routes", routeservice.getAllRoutes()); // System.out.println("update: routeId:"+routeIdOld); session.setAttribute("tripId", trip_detail_id); session.setAttribute("trip", tripDetail); session.setAttribute("routeIdOld", routeIdOld); model.addObject("OroutId", routeIdOld); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/updateTripAction", method = RequestMethod.GET) public String updateTripAction(Model model, HttpServletRequest request, @ModelAttribute("trip") TripDetail tripDetails, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { return "redirect:/j_spring_security_logout"; } // System.out.println("##########"+auth.getName()+"********authenticated: // "+b); TripDetail tripOld1 = tripDetailService.getTripDetail(Integer.parseInt(request.getParameter("trip_id"))); // session.removeAttribute("trip"); int tripId = (Integer) session.getAttribute("tripId"); // System.out.println(); // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addAttribute("date", formatter.format(new Date())); model.addAttribute("login_name", auth.getName()); model.addAttribute("current_page", "trips"); // System.out.println("*********"+request.getParameter("route_name")); if (request.getParameter("route_name").contains(";;")) { // System.out.println("dropdown selected"); String route[] = request.getParameter("route_name").split(";;"); tripDetails.setRouteid((Integer.parseInt(route[0]))); // trip.setRoute_name(route[1]); } else { // if route name checkbox not selected' tripDetails.setTrip_type(tripOld1.getTrip_type()); tripDetails.setRouteid((tripOld1.getRouteid())); // logger.info("trip route d "+trip.getRouteid()); tripDetails.setRoutes(routeservice.getRoute(tripOld1.getRouteid())); tripDetails.setBus(busservice.getBusById(tripOld1.getBusid())); // trip.setRoute_name(tripOld1.getRoute_name()); } // validation for stop timings int tripStartTime = tripDetails.getTrip_start_time_hours() * 60 + tripDetails.getTrip_start_time_minutes(); int tripEndTime = tripDetails.getTrip_end_time_hours() * 60 + tripDetails.getTrip_end_time_minutes(); String bus_id = request.getParameter("bus_id"); // System.out.println(busEntity); if (tripOld1.getBus().getBus_licence_number() != bus_id) { Buses busEntity = busservice.getBusByLicence(bus_id); int status = busEntity.getBus_allotted(); busservice.updateBusStatus(busEntity, ++status); tripDetails.setBusid(busEntity.getBus_id()); Buses old = busservice.getBusByLicence(tripOld1.getBus().getBus_licence_number()); int ol = old.getBus_allotted(); busservice.updateBusStatus(old, --ol); } else { Buses busEntity = busservice.getBusByLicence(bus_id); tripDetails.setBusid(busEntity.getBus_id()); } List<TripDetail> tripsList = tripDetailService.getAllTrips(); for (TripDetail td : tripsList) { if (!(td.getId() == (tripId))) { String tripName = td.getTrip_name(); String tripOldName = tripDetails.getTrip_name(); if (tripName.equals(tripOldName)) { model.addAttribute("error_message", "tripDup"); model.addAttribute("errorOccured", "yes"); model.addAttribute("trip", tripDetails); // model.addAttribute("fs", fs); // model.addAttribute("ls", ls); model.addAttribute("buses", busservice.getBuses()); // model.addAttribute("/school_admin/trip/updatetrip"); return "/school_admin/trip/updatetrip"; } } } // List<Trips> trips = // tripservice.getTripsByBusId(busEntity.getBus_id()); List<TripDetail> trips = tripDetailService.getTripDetailByBusId(tripDetails.getBusid()); // System.out.println("trip by bus: " + trips); for (TripDetail tripSingle : trips) { if (!(tripSingle.getId() == (tripId))) { int triptripSingleStartTime = tripSingle.getTrip_start_time_hours() * 60 + tripSingle.getTrip_start_time_minutes(); int triptripSingleEndTime = tripSingle.getTrip_end_time_hours() * 60 + tripSingle.getTrip_end_time_minutes(); if (tripStartTime >= triptripSingleStartTime && tripStartTime <= triptripSingleEndTime) { // System.out.println("tripEntity"+trip); model.addAttribute("trip", tripDetails); model.addAttribute("error_message", "tripStartTime"); model.addAttribute("errorOccured", "yes"); model.addAttribute("buses", busservice.getBuses()); return "/school_admin/trip/updatetrip"; } if (tripEndTime >= triptripSingleStartTime && tripEndTime <= triptripSingleEndTime) { // System.out.println("tripEntity"+trip); model.addAttribute("trip", tripDetails); model.addAttribute("error_message", "tripEndTime"); model.addAttribute("errorOccured", "yes"); model.addAttribute("buses", busservice.getBuses()); return "/school_admin/trip/updatetrip"; } } } // for /* * String strtTime[] = firstStopTimings.split(":"); int startStopHours = * Integer.parseInt(strtTime[0]); int startStopMinutes = * Integer.parseInt(strtTime[1]); int totalStartStopTime = * startStopHours * 60 + startStopMinutes; * * String secndTime[] = secondStopTimings.split(":"); int endStopHours = * Integer.parseInt(secndTime[0]); int endStopMinutes = * Integer.parseInt(secndTime[1]); int totalEndStopTime = endStopHours * * 60 + endStopMinutes; * * if (tripStartTime >= totalStartStopTime) { // * System.out.println("tripEntity"+trip); model.addAttribute("trip", * tripDetails); model.addAttribute("error_message", "StartTripError"); * model.addAttribute("errorOccured", "yes"); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/updatetrip"; } * * if (tripEndTime <= totalEndStopTime) { * System.out.println("tripEntity" + tripOld1); * model.addAttribute("trip", tripOld1); * model.addAttribute("error_message", "EndTripError"); * model.addAttribute("errorOccured", "yes"); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/updatetrip"; } * * int schoolHours = tripDetails.getSchool_time_hours(); int * schoolMinutes = tripDetails.getSchool_time_minutes(); int * schoolTotalMinutes = schoolHours * 60 + schoolMinutes; * * if (tripDetails.getTrip_type().equals("Pick Up")) { * * if (schoolTotalMinutes <= totalEndStopTime || schoolTotalMinutes >= * tripEndTime) { // System.out.println("tripEntity"+trip); * * model.addAttribute("error_message", "schoolArrivalTimeError"); * model.addAttribute("errorOccured", "yes"); model.addAttribute("trip", * tripDetails); System.out.println(tripDetails); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/updatetrip"; } } * * if (tripDetails.getTrip_type().equals("Drop Off")) { // * System.out.println("inside Drop Off"); if (schoolTotalMinutes <= * tripStartTime || schoolTotalMinutes >= totalStartStopTime) { // * System.out.println("tripEntity"+trip); model.addAttribute("trip", * tripDetails); model.addAttribute("error_message", * "schoolStartTimeError"); model.addAttribute("errorOccured", "yes"); * model.addAttribute("buses", busservice.getBuses()); return * "/school_admin/trip/updatetrip"; } * * } */ int routeIdOld = (Integer) session.getAttribute("routeIdOld"); int currentRouteId = 0; String arr = request.getParameter("route_name"); // System.out.println("route_name " + arr); if (arr.equals("") || arr.equals(null)) { currentRouteId = Integer.parseInt(request.getParameter("current_route")); } else { String a[] = arr.split(";;"); currentRouteId = Integer.parseInt(a[0]); // System.out.println("old routeId: " + routeIdOld + // "current routeID: " + currentRouteId); } if (!(routeIdOld == (currentRouteId))) { tripDetails.setRouteid((currentRouteId)); // System.out.println("route has been changed"); String status = routeservice.getRoute(currentRouteId).getIsAssigned(); int i = Integer.parseInt(status); routeservice.updateStatus(currentRouteId, String.valueOf(++i)); String status1 = routeservice.getRoute(routeIdOld).getIsAssigned(); int i1 = Integer.parseInt(status1); routeservice.updateStatus(routeIdOld, String.valueOf(--i1)); } // System.out.println(trip); tripDetailService.updatetrip(tripId, tripDetails); logger.info("Trip [" + tripDetails.getTrip_name() + " ] got updated....."); // tripsDaoImpl.updateTripByTripId(tripId, trip); // change in student and staff // studentDaoImpl.updateStudentTripNameFromHome(trip.getTrip_name(), // tripId); // studentDaoImpl.updateStudentTripNameFromSchool(trip.getTrip_name(), // tripId); // staffDaoImpl.updateStaffTripNameFromHome(trip.getTrip_name(), // tripId); // staffDaoImpl.updateStaffTripNameFromSchool(trip.getTrip_name(), // tripId); model.addAttribute("trip", tripDetails); return "redirect:/school_admin/trip/trips"; } @RequestMapping(value = "/viewTrip", method = RequestMethod.GET) public ModelAndView viewTrip(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); model.setViewName("/j_spring_security_logout"); return model; } String trip_detail_id = request.getParameter("id"); TripDetail trip = tripDetailService.getTripDetail(Integer.parseInt((trip_detail_id))); model.addObject("trip", trip); model.setViewName("/school_admin/trip/viewtrip"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/deleteTrip", method = RequestMethod.GET) public ModelAndView removeStop(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); model.setViewName("/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.setViewName("/school_admin/trip/removetrip"); Integer trip_detail_id = null; if (request.getParameter("id") != null) { trip_detail_id = Integer.parseInt(request.getParameter("id")); } else { trip_detail_id = Integer.parseInt(request.getSession().getAttribute("id").toString()); } HttpSession session = request.getSession(); session.setAttribute("id", trip_detail_id); TripDetail trip = tripDetailService.getTripDetail(trip_detail_id); model.addObject("trip", trip); model.addObject("login_role", rolesUtility.getRole(request)); request.getSession().removeAttribute("ERROR_MESSAGE"); request.getSession().removeAttribute("id"); return model; } @RequestMapping(value = "/deleteTripAction", method = RequestMethod.POST) public ModelAndView deleteTrip(HttpServletRequest request, ModelAndView view) { Integer trip_detail_id = null; try { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); view.setViewName("redirect:/j_spring_security_logout"); return view; } // System.out.println("delete action"); trip_detail_id = Integer.parseInt(request.getParameter("id")); // changes in routes TripDetail tripDetail = tripDetailService.getTripDetail(trip_detail_id); String tn = tripDetail.getTrip_name(); if (!(tripDetail.equals(null))) { int routeId = tripDetail.getRoutes().getId(); String status = routeservice.getRoute(routeId).getIsAssigned(); int i = Integer.parseInt(status); routeservice.updateStatus(routeId, String.valueOf(--i)); } // System.out.println(trip.getRoute_id()); Buses busEntity = busservice.getBusById(tripDetail.getBus().getBus_id()); int bs = busEntity.getBus_allotted(); busservice.updateBusStatus(busEntity, --bs); // if (tripDetail.getSeats_filled() == 0) System.out.println("Deleting trip_detail_id:" + trip_detail_id); tripDetailService.deleteTripDetail(trip_detail_id); logger.info("Trip [" + tn + " ] got Deleted by User [" + auth.getName() + " ]"); } catch (DataIntegrityViolationException e) { view.addObject("ERROR_MESSAGE", ErrorCodes.CODE_1); logger.error("Exception: " + e.getMessage()); request.getSession().setAttribute("ERROR_MESSAGE", ErrorCodes.CODE_1); request.getSession().setAttribute("id", trip_detail_id); view.setViewName("redirect:/school_admin/trip/deleteTrip"); return view; } catch (Exception e) { logger.error("Exception: " + e.getMessage()); } view.setViewName("redirect:/school_admin/trip/trips"); return view; } // testing purpose @RequestMapping(value = "/getAllRoutesByTripType", method = RequestMethod.POST) public @ResponseBody String getAllRoutesByTripType(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } // System.out.println("inside getallroute method"); String route_type = request.getParameter("trip_type"); // System.out.println(route_type); List<Routes> routes = routeservice.getRouteByType(route_type); // System.out.println(routes); Gson gson = new Gson(); String json = gson.toJson(routes); return json; } public static String firstStopTimings; public static String secondStopTimings; // for first and last stop @RequestMapping(value = "/getAllStopssByRouteId", method = RequestMethod.POST) public @ResponseBody String getAllStopssByRouteId(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } // System.out.println("inside getallroute method "); int route_id = Integer.parseInt(request.getParameter("route_id")); // System.out.println("route id is:"+route_id); // List<RoutesEntity> // routes=tripsDaoImpl.getAllRoutesByTripType(route_type); List<RouteStops> routeStops = routestopservice.getStopsByRouteId(route_id); Collections.sort(routeStops); // System.out.println("size: " + routeStops.size()); if (routeStops.size() > 0) { RouteStops re1 = routeStops.get(0); // System.out.println(re1); String firstStopTime = re1.getStop_time(); int lastStopNumber = routeStops.size(); RouteStops re = routeStops.get(lastStopNumber - 1); // System.out.println(re); String lastStopTime = re.getStop_time(); // System.out.println("firstStopName&lastStopName:"+firstStopTime+";"+lastStopTime); firstStopTimings = firstStopTime; secondStopTimings = lastStopTime; session.setAttribute("fs", firstStopTime); session.setAttribute("ls", lastStopTime); Gson gson = new Gson(); String json = gson.toJson(firstStopTime + ";" + lastStopTime); return json; } else { Gson gson = new Gson(); String json = gson.toJson("none;none"); return json; } } @RequestMapping(value = "/removeAllTripsByTripIds", method = RequestMethod.POST) public @ResponseBody String removeAllTripsByTripIds(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } // System.out.println("inside delete trips method"); String tripIds = request.getParameter("tripIds"); // System.out.println(tripIds); String trips[] = tripIds.split(","); int totalItems = trips.length; // System.out.println(totalItems); for (int i = 1; i <= totalItems; i++) { // StudentEntity se1 = // studentDaoImpl.getStudentByRouteIdFromHome(trips[i - 1]); // StudentEntity se2 = // studentDaoImpl.getStudentByRouteIdFromSchool(trips[i - 1]); // System.out.println("se1"+se1); // System.out.println("se2"+se2); // if ((se1 == null) && (se2 == null)) { // System.out.println("con be deleted"); // before delete, change route status TripDetail trip = tripDetailService.getTripDetail((Integer.parseInt(trips[i - 1]))); if (!(trip.equals(""))) { int routeId = trip.getRoutes().getId(); String status = routeservice.getRoute(routeId).getIsAssigned(); int k = Integer.parseInt(status); routeservice.updateStatus(routeId, String.valueOf(--k)); } Buses busEntity = busservice.getBusById(trip.getBus().getBus_id()); int bs = busEntity.getBus_allotted(); busservice.updateBusStatus(busEntity, --bs); tripDetailService.deleteTripDetail(Integer.parseInt((trips[i - 1]))); logger.info("Trip Deleted"); // } /* * //System.out.println("can be deleted"); * tripsDaoImpl.deleteTrip(trips[i-1]); */ } /* * Gson gson = new Gson(); String json = gson.toJson(routes); return * json; */ // return null; return "trips"; } } <file_sep>package com.main.sts.dto; import java.io.Serializable; public class SOSDTO implements Serializable { int commuter_id; public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Drivers; import com.main.sts.entities.RfidCards; @Repository public class DriversDao extends BaseDao { public List<Drivers> getAllDrivers() { return getAllRecords(Drivers.class); } public void insertDriver(Drivers drivers) { insertEntity(drivers); } public Drivers getDriver(int id) { String queryStr = "from Drivers d where d.id = ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return getSingleRecord(Drivers.class, queryStr, parameters); } public void updateDriver(Drivers driver) { updateEntity(driver); } public void deleteDriver(Drivers driver) { deleteEntity(driver); } public List<Drivers> searchDrivers(String str, String type) { Map<String, Object> restrictions = new HashMap<String, Object>(); restrictions.put(type, "%" + str + "%"); return searchRecords(Drivers.class, restrictions); } } <file_sep>package com.main.sts.service; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.StopsDao; import com.main.sts.dto.RouteStopsDTO; import com.main.sts.dto.StopsDTO; import com.main.sts.entities.RouteStops; import com.main.sts.entities.StopType; import com.main.sts.entities.Stops; @Service public class StopsService { @Autowired private StopsDao stopsdao; @Autowired private RouteStopsService routeStopsSerice; @Autowired private StopTypesService stopTypesService; public List<Stops> getAllStops() { return stopsdao.getStops(); } public void insertStop(Stops stop) { stop.setIsAssigned("0"); stopsdao.insert(stop); } public Stops getStop(int id) { return stopsdao.getStop(id); } public void deleteStop(int id) { Stops stop = getStop(id); stopsdao.deleteStop(stop); } public void deleteStop(Stops stop) { stopsdao.deleteStop(stop); } public Stops getStopName(String name) { return stopsdao.getStopByName(name); } public void updateStop(int id, Stops s) { Stops stop = getStop(id); stop.setGeofence(s.getGeofence()); stop.setIsAssigned(s.getIsAssigned()); stop.setLatitude(s.getLatitude()); stop.setLongitude(s.getLongitude()); stop.setStop_name(s.getStop_name()); stop.setShortcode(s.getShortcode());; stop.setHelp_text(s.getHelp_text());; stop.setImage_path(s.getImage_path());; stop.setDisplay_name(s.getDisplay_name());; stop.setEnabled(s.getEnabled()); stop.setType(s.getType()); stop.setTags(s.getTags()); stop.setStop_type(s.getStop_type()); stopsdao.updateStop(stop); } public void updateStop(Stops stop) { stopsdao.updateStop(stop); } public Stops getStop(String latitude, String longitude) { return stopsdao.getStop(latitude, longitude); } public List<Stops> searchStops(String type, String str) { return stopsdao.searchStops(str, type); } // public List<Stops> getAllAvailableFromStops() { // return routeStopsSerice.getAllAvailableFromStops(); // } public Set<RouteStops> getAllAvailableFromStops() { return routeStopsSerice.getAllAvailableFromStops(); } public List<RouteStops> getAllAvailableToStops(int from_stop_id) { return routeStopsSerice.getAllAvailableToStops(from_stop_id); } public List<RouteStopsDTO> getAllAvailableRoutesWithStops() { List<RouteStopsDTO> routeStops = routeStopsSerice.getAllAvailableRoutesWithStops(true); return routeStops; } public StopsDTO toStopsDTO(RouteStops rs) { List<StopType> stopTypes = stopTypesService.getAllStopTypes(); Map<Integer, StopType> stopTypesMap = new HashMap<Integer, StopType>(); for (StopType stopType : stopTypes) { stopTypesMap.put(stopType.getId(), stopType); } StopsDTO stop = new StopsDTO(); stop.route_stop_id = rs.getId(); stop.stop_id = rs.stop.getId(); stop.stop_name = rs.stop.getDisplay_name();// rs.stop.getStop_name(); stop.latitude = rs.stop.getLatitude(); stop.longitude = rs.stop.getLongitude(); stop.shortcode = rs.stop.getShortcode(); stop.help_text = rs.stop.getHelp_text(); //stop.image_icon_path = rs.stop.getImage_icon_path(); stop.image_path = rs.stop.getImage_path(); stop.tags = rs.stop.getTagsArr(); stop.stop_icon_enabled = rs.stop.getStop_icon_enabled(); StopType st = stopTypesMap.get(rs.stop.getStop_type()); if (st != null) { stop.stop_type_name = st.getStop_type_name(); stop.stop_icon_path = st.getStop_icon_path(); } return stop; } } <file_sep>package com.main.sts.controllers.webapp; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dto.response.AboutUsDTO; import com.main.sts.service.DashBoardSettingsService; @Controller @RequestMapping("/webapp/general") public class SettingsWebAppController { @Autowired private DashBoardSettingsService settingsService; static final Logger logger = Logger.getLogger(SettingsWebAppController.class); @RequestMapping(value = "/about_us", method = RequestMethod.GET) public ModelAndView getAboutUs(ModelAndView model) { AboutUsDTO aboutus = null; try { aboutus = settingsService.getAboutUs(); model.addObject("aboutus", aboutus); } catch (Exception e) { e.printStackTrace(); } model.addObject("current_page", "aboutus"); model.setViewName("/webapp/about_us"); return model; } } <file_sep>package com.main.sts.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.FAQDao; import com.main.sts.entities.BusFarePriceEntity; import com.main.sts.entities.FAQ; @Service("faqService") public class FAQService { @Autowired private FAQDao faqDao; public List<FAQ> findAll() { return faqDao.findAll(); } public FAQ getFAQ(int faq_id) { String query = "from FAQ b where b.id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, faq_id); return faqDao.getSingleRecord(FAQ.class, query, parameters); } public boolean insertFaq(FAQ faq) { return faqDao.insertAFAQ(faq); } public boolean updateAFAQ(int faq_id, String question, String answer) { FAQ faq = getFAQ(faq_id); faq.setQuestion(question); faq.setAnswer(answer); return faqDao.updateAFAQ(faq); } public boolean deleteFAQ(int faq_id) { FAQ faq = getFAQ(faq_id); return faqDao.deleteFAQ(faq); } } <file_sep>package com.ec.eventserver.service; import java.util.Date; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ec.eventserver.dto.request.VehicleGpsDataRequest; import com.ec.eventserver.models.DeviceInfo; import com.main.sts.common.CommonConstants.TripStatus; import com.main.sts.entities.DailyRunningBuses; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.entities.Trips; import com.main.sts.service.BookingService; import com.main.sts.service.BusesService; import com.main.sts.service.DailyBusCoordinatesService; import com.main.sts.service.DailyRunningBusesService; import com.main.sts.service.RouteStopsService; import com.main.sts.service.TripService; @Service("vehicleTrackingHelperService") public class VehicleTrackingHelper { @Autowired private DeviceService deviceService; @Autowired private BusesService vehicleService; @Autowired private TripService tripService; @Autowired private DailyRunningBusesService dailyRunningVehicleService; @Autowired private DailyBusCoordinatesService dailyBusCoordinatesService; @Autowired private EtaProcessor etaProcessor; @Autowired private BookingService bookingService; @Autowired private RouteStopsService routeStopsService; @Autowired private GpsDataProcess gpsDataProcess; // public void handleIncomingMessage(VehicleGpsDataRequest gpsData, boolean startingTrip) { // String device_id = gpsData.getDevice_id(); // Trips trip = findCurrentVehicleTrip(device_id); // if (trip == null) { // System.out.println("No trip found in system for device_id:" + device_id); // } else { // if (gpsData.getVehicle_id() == null) { // gpsData.setVehicle_id(trip.getTripDetail().getBusid()); // } // DailyRunningBuses dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), // gpsData.getCreated_at(), TripStatus.RUNNING); // if (dailyRunningBus == null) { // // trip not started // System.out.println("daily bus is null"); // dailyRunningVehicleService.startDailyRunningBus(trip, gpsData); // } else { // // for running trip // processData(dailyRunningBus, trip, gpsData); // } // } // } // public void handleIncomingMessage(VehicleGpsDataRequest gpsData, TripStatus tripStatus) { // String device_id = gpsData.getDevice_id(); // Integer trip_id = gpsData.getTrip_id(); // // Trips trip = null; // if (trip_id != null) { // trip = tripService.getTrip(trip_id);; // } // if (tripStatus == TripStatus.STARTING_TRIP) { // startTrip(trip); // } // //// if (trip == null) { //// System.out.println("No trip found in system for device_id:" + device_id); //// System.out.println("Trying to find the trip through mapping for " + device_id); //// trip = findCurrentVehicleTrip(device_id); //// } // // if (trip == null) { // System.out.println("No trip found in system for device_id:" + device_id); // handleNonRunningTripTracking(); // } else { // // } // // if (trip == null) { // System.out.println("No trip found in system for device_id:" + device_id); // } else { // if (gpsData.getVehicle_id() == null) { // gpsData.setVehicle_id(trip.getTripDetail().getBusid()); // } // DailyRunningBuses dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), // gpsData.getCreated_at(), TripStatus.RUNNING); // if (dailyRunningBus == null) { // // trip not started // System.out.println("daily bus is null"); // dailyRunningVehicleService.startDailyRunningBus(trip, gpsData); // } else { // // for running trip // processData(dailyRunningBus, trip, gpsData); // } // // if (tripStatus == TripStatus.ENDING_TRIP) { // endTrip(dailyRunningBus); // } // } // } public void handleIncomingMessage(VehicleGpsDataRequest gpsData, TripStatus tripStatus) { String device_id = gpsData.getDevice_id(); Integer trip_id = gpsData.getTrip_id(); Trips trip = null; if (trip_id != null) { trip = tripService.getTrip(trip_id);; } // if (trip == null) { // System.out.println("No trip found in system for device_id:" + // device_id); // System.out.println("Trying to find the trip through mapping for " + // device_id); // trip = findCurrentVehicleTrip(device_id); // } if (trip == null) { System.out.println("No trip found in system for device_id:" + device_id); handleNonRunningTripTracking(gpsData); } else { // Adding vehicle information. addVehicle(trip, gpsData); switch (tripStatus) { case STARTING_TRIP : startTrip(trip, gpsData); break; case RUNNING : handleRunningTrip(trip, gpsData); break; case ENDING_TRIP : endTrip(trip, gpsData); break; default : break; } } } private void addVehicle(Trips trip, VehicleGpsDataRequest gpsData) { if (gpsData.getVehicle_id() == null) { gpsData.setVehicle_id(trip.getTripDetail().getBusid()); } } public void startTrip(Trips trip, VehicleGpsDataRequest gpsData) { System.out.println("startTrip:Got a message for starting trip id:" + trip.getId()); DailyRunningBuses dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), gpsData.getCreated_at(), TripStatus.RUNNING); if (dailyRunningBus == null) { // trip not started System.out .println("daily bus is null so creating an entry for: trip:" + trip.getId() + "and starting trip"); dailyRunningVehicleService.startDailyRunningBus(trip, gpsData); // adding coordinates for trip processData(dailyRunningBus, trip, gpsData); } else { // for running trip handleRunningTrip(trip, gpsData); } } public void handleRunningTrip(Trips trip, VehicleGpsDataRequest gpsData) { System.out.println("handleRunningTrip..."); String device_id = gpsData.getDevice_id(); if (trip == null) { System.out.println("No trip found in system for device_id:" + device_id); //throw new IllegalArgumentException("No trip found in system for device_id:" + device_id+" It can't be null"); System.out.println("=================== STARTING TRIP===============device_id:" + device_id); startTrip(trip, gpsData); } System.out.println("handleRunningTrip: for trip id:" + trip.getId()); DailyRunningBuses dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), gpsData.getCreated_at(), TripStatus.RUNNING); if (dailyRunningBus == null) { // trip not started System.out.println("daily bus is null"); throw new IllegalArgumentException("DailyRunningBuses shouldnt be null for tripid:"+trip.getId()+"---device_id:"+device_id); } // for running trip processData(dailyRunningBus, trip, gpsData); } public void endTrip(Trips trip, VehicleGpsDataRequest gpsData){ System.out.println("endTrip:Got a message for ending a trip id:" + trip.getId()); DailyRunningBuses dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), gpsData.getCreated_at()); if (dailyRunningBus == null) { // trip not started System.out.println("daily bus is null"); throw new IllegalArgumentException("DailyRunningBuses shouldnt be null"); } TripStatus tripStatus = TripStatus.getTripStatus(dailyRunningBus.getTrip_status()); // adding coordinates for trip processData(dailyRunningBus, trip, gpsData); // a trip should running before it can be ended if (tripStatus == TripStatus.STARTING_TRIP || tripStatus == TripStatus.RUNNING) { int dailyRunningBusId = dailyRunningBus.getId(); String endTime = null; Date d = new Date(); endTime = d.getHours() + ":" + d.getMinutes(); System.out.println("endTime:" + endTime); dailyRunningVehicleService.updateTripEndTime(dailyRunningBusId, endTime); // marking expirary of all bookings bookingService.markBookingExpired(trip.getId()); } else { System.out.println("tripStatus: in endTrip:" + tripStatus); if (tripStatus == TripStatus.ENDING_TRIP) { System.out.println("trip already ended. it seems we got 2 end trip call"); alreadyEndedTrip(trip, gpsData); } } } /** * Handling Already ended trip * @param trip * @param gpsData */ public void alreadyEndedTrip(Trips trip, VehicleGpsDataRequest gpsData) { handleNonRunningTripTracking(gpsData); } public void handleNonRunningTripTracking(VehicleGpsDataRequest gpsData) { String device_id = gpsData.getDevice_id(); System.out.println("No trip found in system for device_id:" + device_id); } public Trips findCurrentVehicleTrip(String device_id) { DeviceInfo deviceInfo = deviceService.getDeviceInfoByECDeviceId(device_id); int vehicle_id = deviceInfo.getVehicle_id(); // Date Date today = new Date(); // today.setHours(0); // today.setMinutes(0); // today.setSeconds(0); Trips trip = tripService.getTripByVehicleIdAndRunningDate(vehicle_id, today); return trip; } public void processData(DailyRunningBuses dailyRunningBus, Trips trip, VehicleGpsDataRequest gpsData) { dailyRunningBus = dailyRunningVehicleService.getDailyRunningBus(trip.getId(), gpsData.getCreated_at(), TripStatus.RUNNING); //if (properties.getIs_eta_required().equals("true")) { etaProcessor.procesEta(gpsData, trip, dailyRunningBus); //} // // Gps Data and process it gpsDataProcess.process(gpsData, trip, dailyRunningBus); dailyBusCoordinatesService.insertDailyBusCoordinates(gpsData, trip.getId()); // gpsDataProcess.checkDriverSpeed(context, deviceData, trip); // checking for the current location if it is a stop checkForStopAndTakeAction(trip, gpsData); } public void checkForStopAndTakeAction(Trips trip, VehicleGpsDataRequest gpsData) { Stops reachedStop = checkForBusStopLocation(trip, gpsData); // sending message to all user those are goign to dropoff if (reachedStop != null) { // Only if the current stop is dropoff stop for some commuetrs, // they will receive this message. for thank you for riding with us. bookingService.markBookingExpired(trip.getId(), reachedStop.getId(), true); } if(reachedStop!=null){ // TODO: Pending //bookingService.notifyUserAboutPickupPoint(trip.getId(), reachedStop.getId(), true); } } public Stops checkForBusStopLocation(Trips trip, VehicleGpsDataRequest gpsData) { int route_id = trip.getTripDetail().getRouteid(); Set<RouteStops> routeStops = routeStopsService.getAllAvailableFromStops(route_id); Stops reachedStop = null; for (RouteStops rs : routeStops) { Stops stop = rs.getStop(); double lat1 = Double.parseDouble(stop.getLatitude()); double long1 = Double.parseDouble(stop.getLongitude()); double lat2 = gpsData.getGps_lat(); double long2 = gpsData.getGps_long(); double distanceInMeters = distance(lat1, lat2, long1, long2, 0, 0); distanceInMeters = (distanceInMeters < 0 ? -distanceInMeters : distanceInMeters); System.out.println("distanceInMeters:"+distanceInMeters+" name:"+stop.getStop_name()+"--"); if (distanceInMeters < 50) { reachedStop = stop; break; } } return reachedStop; } // public void processData(DailyRunningBuses dailyRunningBus, Trips trip, // DeviceData deviceData, // SystemProperties properties) { // boolean is_rfid_valid = !(deviceData.getRfid_number().equals("0")); // dailyRunningBus = // dailyRunningBusesService.getDailyRunningBus(trip.getId(), // deviceData.getDate(), "running"); // logger.info("Trip Running --> " + dailyRunningBus); // // trip started already // if (is_rfid_valid) { // // RFID data and process it // rfidDataProcess.process(deviceData, trip, dailyRunningBus); // } // // Gps Data and process it // gpsDataProcess.process(deviceData, trip, dailyRunningBus); // // //System.out.println(properties + ",,,,,,,,,,,,,,"); // if (properties.getIs_eta_required().equals("true")) { // etaProcees.procesEta(deviceData, trip, dailyRunningBus); // } // // /* // * Insert daily bus coordinates // * // * Start here // */ // // dailyBusCoordinatesService.insertDailyBusCoordinates(deviceData, // trip.getId()); // // /* // * Insert daily bus coordinates // * // * Start here // */ // // /* // * if (properties.getIs_eta_required().equals("true")) { // * etaProcees.procesEta(deviceData, trip, dailyRunningBus); // * // * // * } // */ // gpsDataProcess.checkDriverSpeed(context, deviceData, trip); // // } // public Trips findCurrentBusTrip(DeviceData data, ApplicationContext // context) throws ParseException { // // List<Trips> trips = tripService.getTripsByBusId(data.getBus_id()); // Date start = null, end = null; // Date device_time = getTime.getDate(data.getTime()); // Trips current_trip = null; // DailyRunningBuses daily = null; // //logger.info("trips "+trips.size()); // for (Trips trip : trips) { // daily = dailyRunningBusesService.getDailyRunningBus(trip.getId(), // data.getDate(), "running"); // start = getTime.getDate(trip.getTrip_start_time_hours() + ":" + // (trip.getTrip_start_time_minutes() - 1)); // if(daily!=null) // end = getTime.getDate(daily.getTrip_end_time()); // else // end=getTime.getDate(trip.getTrip_end_time_hours() + ":" + // (trip.getTrip_end_time_minutes() +1)); // //System.out.println(start + " -- " + end + " -- " + device_time); // if(daily!=null){ // if (device_time.equals(end)||device_time.after(end)) { // // /*EtaProcess eta = etaProcessService.getlastEta(trip.getId(), // data.getDate()); // if (eta != null) // tripExtension.etaNotNull(eta, data, trip, daily); // else*/ // trip=tripExtension.etaNull(data, trip, daily); // end = getTime.getDate(daily.getTrip_end_time()); // } // } // if (device_time.after(start) && device_time.before(end)) { // current_trip = trip; // break; // } // // // } // return current_trip; // // } // public void handleDeviceMessage(DeviceData deviceData, SystemProperties // properties) throws ParseException { // Buses bus = // busesService.getBusByLicence(deviceData.getBus_licence_number()); // // if (bus == null) { // logger.info("Bus Licence received [ " + // deviceData.getBus_licence_number() // + " ] is not found in database { Action: Ignoring data }"); // } else { // deviceData.setBus_id(bus.getBus_id()); // // logger.info(deviceData); // BusTripController busTripFinder = // context.getBean(BusTripController.class); // Trips trip = busTripFinder.findCurrentBusTrip(deviceData, context); // if (trip == null) { // logger.info("No trip found for bus [ " + // deviceData.getBus_licence_number() + " ]"); // } else { // boolean is_rfid_valid = !(deviceData.getRfid_number().equals("0")); // // DailyRunningBuses dailyRunningBus = // dailyRunningBusesService.getDailyRunningBus(trip.getId(), // deviceData.getDate(), "running"); // if (dailyRunningBus == null) { // // trip not started // logger.info("daily bus is null"); // // deviceData.getRfid_number().equals("????????????????") // if (is_rfid_valid) { // logger.info("rfid is ok"); // // RFID data, and start trip // dailyRunningBusesService.startDailyRunningBus(trip, deviceData); // } else { // // logger.info("Trip Error: Trip not started yet.."); // } // } else { // processData(dailyRunningBus, trip, deviceData, properties); // } // // } // } // // } /* * Calculate distance between two points in latitude and longitude taking * into account height difference. If you are not interested in height * difference pass 0.0. Uses Haversine method as its base. * * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters * el2 End altitude in meters * @returns Distance in Meters */ public static double distance(double lat1, double lat2, double lon1, double lon2, double el1, double el2) { final int R = 6371; // Radius of the earth Double latDistance = Math.toRadians(lat2 - lat1); Double lonDistance = Math.toRadians(lon2 - lon1); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double distance = R * c * 1000; // convert to meters double height = el1 - el2; distance = Math.pow(distance, 2) + Math.pow(height, 2); return Math.sqrt(distance); } } <file_sep>package com.main.sts.dto.response; public class SaveRoutesResponseDTO { Integer commuter_id; Integer from_stop_id; Integer to_stop_id; Integer booking_id; public Integer getBooking_id() { return booking_id; } public void setBooking_id(Integer booking_id) { this.booking_id = booking_id; } public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getFrom_stop_id() { return from_stop_id; } public void setFrom_stop_id(Integer from_stop_id) { this.from_stop_id = from_stop_id; } public Integer getTo_stop_id() { return to_stop_id; } public void setTo_stop_id(Integer to_stop_id) { this.to_stop_id = to_stop_id; } @Override public String toString() { return "SavedRouteDTO [commuter_id=" + commuter_id + ", from_stop_id=" + from_stop_id + ", to_stop_id=" + to_stop_id + "]"; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Users_Roles; @Repository public class Users_RolesDao extends BaseDao { public void insertIntoUser_Roles(Users_Roles users_roles) { insertEntity(users_roles); } public Users_Roles getUserByUserId(int user_id) { String queString = "from Users_Roles u where u.user_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, user_id); return getSingleRecord(Users_Roles.class, queString, parameters); } public Users_Roles getUserByRoleId(int role_id) { String queString = "from Users_Roles u where u.role_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, role_id); return getSingleRecord(Users_Roles.class, queString, parameters); } public void deleteUser(Users_Roles user) { deleteEntity(user); } public List<Users_Roles> getRecords() { return getAllRecords(Users_Roles.class); } public void updateUser_Roles(Users_Roles users_Roles) { updateEntity(users_Roles); } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.Drivers; import com.main.sts.service.DriversService; import com.main.sts.service.RfidCardsService; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/persons") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class DriversController { private static final Logger logger = Logger.getLogger(DriversController.class); @Autowired private RolesUtility rolesUtility; @Autowired private RfidCardsService rfidCardsService; @Autowired private DriversService driversService; @RequestMapping(value = "/drivers", method = RequestMethod.GET) public ModelAndView driversHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/persons/drivers"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); List<Drivers> drivers = driversService.listDrivers(); model.addObject("drivers", drivers); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/drivers/add", method = RequestMethod.GET) public ModelAndView seniorHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/persons/adddriverform"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("drivers_rfid_list", rfidCardsService.getAvailableRfids("driver", 0)); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); // generating country names String[] locales = Locale.getISOCountries(); List<String> countries = new LinkedList<String>(); for (String countryCode : locales) { Locale obj = new Locale("", countryCode); countries.add(obj.getDisplayCountry()); } Collections.sort(countries); model.addObject("countries", countries); // country name code end model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/drivers/adddriveraction", method = RequestMethod.POST) public ModelAndView addDriverAction(ModelAndView model, HttpServletRequest request, @ModelAttribute Drivers driverentity) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } try { Drivers driver = (Drivers) driversService.addDriver(request); // logger.info(driversService.listDrivers()); logger.info("Driver [ " + request.getParameter("driver_name") + " ] has been added with Rfid [ " + request.getParameter("driver_rfid_number") + " ]"); rfidCardsService.updateRfidWhenAllocated(driver.getId(), driver.getDriver_name(), driver.getRfid_number()); logger.info("Rfid [ " + request.getParameter("driver_rfid_number") + " ] allocated to driver [ " + request.getParameter("driver_name") + " ] with Driver Id [ " + request.getParameter("driver_name") + " ] "); // System.out.println(" driver based on rfid "+driverEntity); model.setViewName("redirect:/school_admin/persons/drivers"); model.addObject("message", "driver_add_success"); model.addObject("driver_name", request.getParameter("driver_name")); } catch (Exception e) { model.addObject("driver_name", request.getParameter("driver_name")); model.setViewName("redirect:/school_admin/persons/adddriverform"); model.addObject("message", "driver_add_success"); e.printStackTrace(); } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); model.addObject("date", formatter.format(new Date())); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/drivers/updatedriver", method = RequestMethod.GET) public ModelAndView UpdateDriver(ModelAndView model, HttpServletRequest request, HttpSession session) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/persons/updatedriver"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("drivers_rfid_list", rfidCardsService.getAvailableRfids("driver", 0)); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); int driver_id = Integer.parseInt(request.getParameter("id")); Drivers driver = driversService.getDriver(driver_id); model.addObject("driver", driver); session.setAttribute("oldDriver", driver); // generating country names String[] locales = Locale.getISOCountries(); List<String> countries = new LinkedList<String>(); for (String countryCode : locales) { Locale obj = new Locale("", countryCode); countries.add(obj.getDisplayCountry()); } Collections.sort(countries); model.addObject("countries", countries); // country name code end model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/drivers/updatedriveraction", method = RequestMethod.POST) public ModelAndView updateDriverAction(ModelAndView model, HttpServletRequest request, @ModelAttribute Drivers driver) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } String new_rfid_number = request.getParameter("driver_rfid_number"); // System.out.println(new_rfid_number); try { driversService.updateDriver(driver, new_rfid_number); // update // driver // here model.setViewName("redirect:/school_admin/persons/drivers"); } catch (Exception e) { e.printStackTrace(); } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); model.addObject("date", formatter.format(new Date())); return model; } @RequestMapping(value = "/drivers/removedriver", method = RequestMethod.GET) public ModelAndView removeDriver(ModelAndView model, HttpServletRequest request) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/persons/removedriver"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); // model.addObject("drivers_rfid_list",rfidCardsService.getAvailableRfids("driver", // 0)); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); int id = Integer.parseInt(request.getParameter("id")); Drivers driver = driversService.getDriver(id); // //System.out.println(driver); model.addObject("driver", driver); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/drivers/removedriveraction", method = RequestMethod.POST) public ModelAndView removeDriverAction(ModelAndView model, HttpServletRequest request) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } int id = Integer.parseInt(request.getParameter("driver_id")); String driver_rfid_number = request.getParameter("rfid_number"); Drivers driver = driversService.getDriver(id); try { rfidCardsService.updateRfidWhenDeallocated(driver_rfid_number); logger.info("Rfid [ " + driver_rfid_number + " ] de-allocated from driver [ " + driver.getDriver_name() + " ] with Driver Id [ " + driver.getDriver_id() + " ] "); driversService.deleteDriver(id); logger.info("Driver [ " + driver.getDriver_name() + " ] with Driver ID [ " + driver.getDriver_id() + " ] has been deleted"); model.setViewName("redirect:/school_admin/persons/drivers"); } catch (Exception e) { model.setViewName("redirect:/school_admin/persons/removedriverform"); e.printStackTrace(); } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); model.addObject("date", formatter.format(new Date())); return model; } @RequestMapping(value = "/driver/viewdriver", method = RequestMethod.GET) public ModelAndView viewDriver(ModelAndView model, HttpServletRequest request) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } int id = Integer.parseInt(request.getParameter("id")); model.addObject("driverInfo", driversService.getDriver(id)); model.setViewName("/school_admin/persons/viewDriver"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "staff_list"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } // search students starts @RequestMapping(value = "/driver/search", method = RequestMethod.POST) public @ResponseBody String searchStudent(HttpServletRequest request, Model model, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String value = request.getParameter("searchkey"); String searchOption = request.getParameter("searchOption"); // System.out.println("value "+value+" option "+searchOption); List<Drivers> searchDrivers = null; if (searchOption.equalsIgnoreCase("rfid_number")) { searchDrivers = driversService.searchDrivers(value, searchOption); } else if (searchOption.equalsIgnoreCase("driver_name")) { searchDrivers = driversService.searchDrivers(value, searchOption); } else if (searchOption.equalsIgnoreCase("phone")) { // System.out.println("search by phone:"+rfid_number); // searchDrivers = driverDaoImpl.searchDriversByPhone(rfid_number); // System.out.println(searchDrivers); } session.setAttribute("searchDrivers", searchDrivers); return "/sts/school_admin/persons/driverSearch"; } @RequestMapping(value = "/driverSearch", method = RequestMethod.GET) public ModelAndView studentSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/persons/drivers"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "drivers_list"); List<Drivers> searchDriversList = (List<Drivers>) session.getAttribute("searchDrivers"); model.addObject("drivers", searchDriversList); if (searchDriversList == null) { model.addObject("drivers", driversService.listDrivers()); model.addObject("error_message", "noMatching"); } return model; } // search students ends @RequestMapping(value = "/removeAllDriversById", method = RequestMethod.POST) public @ResponseBody String removeAllDriversById(ModelAndView model, HttpServletRequest request) { // System.out.println("inside delete drivers method"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String driverIds = request.getParameter("driverIds"); // //System.out.println(driverIds); String driverIdsArray[] = driverIds.split(","); int totalItems = driverIdsArray.length; // //System.out.println(totalItems); for (int i = 1; i <= totalItems; i++) { // System.out.println("driver deleted ids: "+driverIdsArray[i-1]); Drivers entity = driversService.getDriver(Integer.parseInt(driverIdsArray[i - 1])); driversService.deleteDriver(entity); logger.info("Driver [ " + entity.getDriver_name() + " ] deleted from drivers list"); rfidCardsService.updateRfidWhenDeallocated(entity.getRfid_number()); } // return null; return "drivers"; } }// class <file_sep>package com.ec.eventserver.dto.request; import java.io.Serializable; import java.util.Date; import com.main.sts.entities.Buses; import com.main.sts.entities.Trips; import com.main.sts.service.BusesService; import com.main.sts.service.TripService; public class VehicleGpsDataRequest implements Serializable { String device_id; double gps_lat; double gps_long; Integer trip_id; Integer vehicle_id; double vehicle_speed; private Date created_at; private String time; public String getDevice_id() { return device_id; } public void setDevice_id(String device_id) { this.device_id = device_id; } public double getGps_lat() { return gps_lat; } public void setGps_lat(double gps_lat) { this.gps_lat = gps_lat; } public double getGps_long() { return gps_long; } public void setGps_long(double gps_long) { this.gps_long = gps_long; } public Integer getTrip_id() { return trip_id; } public void setTrip_id(Integer trip_id) { this.trip_id = trip_id; } public Integer getVehicle_id() { return vehicle_id; } public void setVehicle_id(Integer vehicle_id) { this.vehicle_id = vehicle_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public double getVehicle_speed() { return vehicle_speed; } public void setVehicle_speed(double vehicle_speed) { this.vehicle_speed = vehicle_speed; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Buses getVehicle(BusesService vehicleService, TripService tripService) { if (trip_id != null) { Trips trip = tripService.getTrip(trip_id); int vehicle_id = trip.getTripDetail().getBusid(); Buses buses = vehicleService.getBusById(vehicle_id); return buses; } return null; } public String getEventTimeInHoursMins() { String current_time = created_at.getHours() + ":" + created_at.getMinutes(); return current_time; } } <file_sep>package com.main.sts; import java.util.List; import java.util.Set; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.entities.Feedback; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.service.FeedbackService; import com.main.sts.service.RouteStopsService; public class FeedbackServiceTest extends BaseTest { @Resource private FeedbackService feedbackService; @Test public void testFindAll() { //Assert.assertFalse(feedbackService.findAll().isEmpty()); for (Feedback c : feedbackService.findAll()) { System.out.println(c.getReason()); } } // @Test // public void testFindAllAvailableToStops() { // int stop_id = 741; // Set<RouteStops> routeStops = feedback.getAllAvailableToStops(stop_id); // for (RouteStops rs : routeStops) { // System.out.println(rs.getId()+"--"+rs.getStop_number() +"--"+rs.getStop().getStop_name()); // } // } // } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Stops; @Repository public class StopsDao extends BaseDao { public List<Stops> getStops() { return getAllRecords(Stops.class); } public void insert(Stops stop) { insertEntity(stop); } public Stops getStop(int id) { String query = "from Stops s where s.id=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, id); return getSingleRecord(Stops.class, query, parameter, true); } public Stops getStopByName(String name) { String query = "from Stops s where s.stop_name=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, name); return getSingleRecord(Stops.class, query, parameter, true); } public void deleteStop(Stops stop) { deleteEntity(stop); } public void updateStop(Stops stop) { updateEntity(stop); } public Stops getStop(String latitude, String longitude) { String query = "from Stops s where s.latitude=? and s.longitude=?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, latitude); parameter.put(1, longitude); return getSingleRecord(Stops.class, query, parameter, true); } public List<Stops> searchStops(String str, String type) { Map<String, Object> restrictions = new HashMap<String, Object>(); restrictions.put(type, "%" + str + "%"); return searchRecords(Stops.class, restrictions); } } <file_sep>package com.main.sts; import java.util.List; import java.util.Set; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.entities.RouteStops; import com.main.sts.service.StopsService; public class StopServiceTest extends BaseTest { @Resource private StopsService stopService; @Test public void findAllStops() { Assert.assertFalse(stopService.getAllStops().isEmpty()); Assert.assertFalse(stopService.getAllAvailableFromStops().isEmpty()); } @Test public void findToStops(){ List<RouteStops> routeStopsList = null; int from_stop_id = 1;//129; try { routeStopsList = stopService.getAllAvailableToStops(from_stop_id); } catch (Exception e) { e.printStackTrace(); } for (RouteStops routeStops : routeStopsList) { System.out.println(routeStops.getRoute_id() +"--"+routeStops.getStop().getStop_name()); } } @Test public void findFromStops() { List<RouteStops> routeStopsList = null; int from_stop_id = 1;// 129; try { routeStopsList = stopService.getAllAvailableToStops(from_stop_id); } catch (Exception e) { e.printStackTrace(); } for (RouteStops routeStops : routeStopsList) { System.out.println(stopService.toStopsDTO(routeStops)); } } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.DailyDriverData; @Repository public class DailyDriverDataDao extends BaseDao { public DailyDriverData getDailyDriverData(int id) { String queryStr = "from DailyDriverData d where d.id = ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return getSingleRecord(DailyDriverData.class, queryStr, parameters); } public void insertDailyDriverData(DailyDriverData dailyDriverData) { insertEntity(dailyDriverData); } public DailyDriverData getDailyDriverData(int trip_id, String date) { String queryStr = "from DailyDriverData d where d.trip_id = ? and date = ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, trip_id); parameters.put(1, date); return getSingleRecord(DailyDriverData.class, queryStr, parameters); } public DailyDriverData getDailyDriverData(int trip_id, int driver_id, String date) { String queryStr = "from DailyDriverData d where d.trip_id = ? and date = ? and in_driver_id = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, trip_id); parameters.put(1, date); parameters.put(2, driver_id); return getSingleRecord(DailyDriverData.class, queryStr, parameters); } public List<DailyDriverData> getDriverData(String date) { String queryStr = "from DailyDriverData d where d.date = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, date); return getRecords(DailyDriverData.class, queryStr, parameters); } public List<DailyDriverData> getDriverDetails(String name, String date) { String queryStr = "from DailyDriverData d where d.date = ? and out_driver_name = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, date); parameters.put(1, name); return getRecords(DailyDriverData.class, queryStr, parameters); } } <file_sep>package com.main.sts.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dao.sql.FareDao; import com.main.sts.entities.BusFarePriceEntity; import com.main.sts.entities.Stops; import com.main.sts.service.StopsService; @Controller @RequestMapping(value = "/school_admin/busfareprices") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class BusFarePriceController { @Autowired private StopsService stopservice; @Autowired private FareDao busFarePriceDao; @RequestMapping(value = "/busfareprices_list", method = RequestMethod.GET) public ModelAndView busFarePriceHome(ModelAndView model) { List<BusFarePriceEntity> busFarePriceEntities = busFarePriceDao.findAll(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/busfareprices/busfareprices_list"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("busFarePriceEntities", busFarePriceEntities); return model; } @RequestMapping(value = "/busfareprices_list/add", method = RequestMethod.GET) public ModelAndView busFarePriceHomeAdd(ModelAndView model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } List<Stops> stops = stopservice.getAllStops(); model.setViewName("/school_admin/busfareprices/add"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("stops", stops); return model; } @RequestMapping(value = "/busfareprices_list/addaction", method = RequestMethod.POST) public ModelAndView busFarePriceHomeAddAction(ModelAndView model, @ModelAttribute BusFarePriceEntity entity) { busFarePriceDao.insertEntity(entity); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } List<Stops> stops = stopservice.getAllStops(); model.setViewName("redirect:/school_admin/busfareprices/busfareprices_list"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("stops", stops); return model; } @RequestMapping(value = "/removbusFarePriceEntitiesById", method = RequestMethod.POST) public @ResponseBody String removeAllStudentsById(ModelAndView model, HttpServletRequest request) { // System.out.println("inside delete students method"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String stuIdsArray[] = request.getParameter("ids").split(","); for (int i = 0; i <= stuIdsArray.length - 1; i++) { try { int fare_id = Integer.parseInt(stuIdsArray[i].trim()); busFarePriceDao.deleteFare(fare_id); } catch (Exception e) { e.printStackTrace(); } } return "busfareprices_list"; } @RequestMapping(value = "/update", method = RequestMethod.GET) public ModelAndView busFarePriceHomeUpdate(ModelAndView model, HttpServletRequest requ) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } List<Stops> stops = stopservice.getAllStops(); int fare_id = Integer.parseInt(requ.getParameter("id")); //String queryStr = "from BusFarePriceEntity r where r.fare_id = ?"; //Map<Integer, Object> parameters = new HashMap<Integer, Object>(); //parameters.put(0, Integer.parseInt(requ.getParameter("id"))); BusFarePriceEntity busFarePriceEntity = busFarePriceDao.getFareById(fare_id); model.setViewName("/school_admin/busfareprices/update"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("busFarePriceEntity", busFarePriceEntity); model.addObject("stops", stops); return model; } @RequestMapping(value = "/updateaction", method = RequestMethod.POST) public ModelAndView busFarePriceHomUpdateAction(ModelAndView model, @ModelAttribute BusFarePriceEntity entity) { busFarePriceDao.updateEntity(entity); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } List<Stops> stops = stopservice.getAllStops(); model.setViewName("redirect:/school_admin/busfareprices/busfareprices_list"); model.addObject("login_name", auth.getName()); model.addObject("current_page", "buses_list"); model.addObject("stops", stops); return model; } } <file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="transport") public class Transport { @Id @GeneratedValue private Integer id; private String subscriber_type; private int subscriber_id; private String transport_type; private Integer bus_id; private Integer route_id; private Integer trip_id; private Integer stop_id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSubscriber_type() { return subscriber_type; } public void setSubscriber_type(String subscriber_type) { this.subscriber_type = subscriber_type; } public int getSubscriber_id() { return subscriber_id; } public void setSubscriber_id(int subscriber_id) { this.subscriber_id = subscriber_id; } public Integer getBus_id() { return bus_id; } public void setBus_id(Integer bus_id) { this.bus_id = bus_id; } public Integer getRoute_id() { return route_id; } public void setRoute_id(Integer route_id) { this.route_id = route_id; } public Integer getTrip_id() { return trip_id; } public void setTrip_id(Integer trip_id) { this.trip_id = trip_id; } public Integer getStop_id() { return stop_id; } public void setStop_id(Integer stop_id) { this.stop_id = stop_id; } public String getTransport_type() { return transport_type; } public void setTransport_type(String transport_type) { this.transport_type = transport_type; } @Override public String toString() { return "Transport [id=" + id + ", subscriber_type=" + subscriber_type + ", subscriber_id=" + subscriber_id + ", transport_type=" + transport_type + ", bus_id=" + bus_id + ", route_id=" + route_id + ", trip_id=" + trip_id + ", stop_id=" + stop_id + "]"; } } <file_sep>package com.main.sts.dto.response; import java.io.Serializable; import com.main.sts.service.ReturnCodes; public class BookingCancellationResponse implements Serializable { Integer booking_id; Integer commuter_id; Integer refunded_points; Integer refunded_free_rides; Integer account_balance; Integer free_rides_balance; ReturnCodes returnCode; public Integer getBooking_id() { return booking_id; } public void setBooking_id(Integer booking_id) { this.booking_id = booking_id; } public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getRefunded_points() { return refunded_points; } public void setRefunded_points(Integer refunded_points) { this.refunded_points = refunded_points; } public Integer getAccount_balance() { return account_balance; } public void setAccount_balance(Integer account_balance) { this.account_balance = account_balance; } public ReturnCodes getReturnCode() { return returnCode; } public void setReturnCode(ReturnCodes returnCode) { this.returnCode = returnCode; } public Integer getRefunded_free_rides() { return refunded_free_rides; } public void setRefunded_free_rides(Integer refunded_free_rides) { this.refunded_free_rides = refunded_free_rides; } public Integer getFree_rides_balance() { return free_rides_balance; } public void setFree_rides_balance(Integer free_rides_balance) { this.free_rides_balance = free_rides_balance; } } <file_sep>package com.main.sts.dao.sql; import java.io.Serializable; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.main.sts.common.CommonConstants.TransactionAction; import com.main.sts.common.CommonConstants.TransactionBy; import com.main.sts.common.CommonConstants.TransactionStatus; import com.main.sts.common.CommonConstants.TransactionType; import com.main.sts.entities.Booking; import com.main.sts.entities.TransactionInfo; import com.main.sts.util.LogUtil; @Repository public class TransactionDao extends BaseDao { @Autowired private AccountDao accountDao; public List<TransactionInfo> findAll() { return getAllRecords(TransactionInfo.class); } public TransactionInfo findTransactionById(int tx_id) { String query = "from TransactionInfo b where b.id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, tx_id); return getSingleRecord(TransactionInfo.class, query, parameters); } public List<TransactionInfo> findTransactionByCommuterId(int commuter_id, Integer offset, Integer limit) { System.out.println("finding transaction for:"+commuter_id); if (limit == null) { limit = 10; } if (offset == null) { offset = 0; } String query = null; //if (limit != -1) { query = "from TransactionInfo b where b.commuter_id=? order by created_at desc"; //} System.out.println("query:"+query); Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getRecords(TransactionInfo.class, query, parameters, offset, limit); } public List<TransactionInfo> findTransactionByCommuterId(int commuter_id) { System.out.println("finding transaction for:"+commuter_id); String query = null; //if (limit != -1) { query = "from TransactionInfo b where b.commuter_id=? order by created_at desc"; //} System.out.println("query:"+query); Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getRecords(TransactionInfo.class, query, parameters); } // public List<TransactionInfo> findTransactionByCommuterId(int commuter_id, Integer offset, Integer limit) { // return findTransactionByCommuterId(commuter_id, offset, 10); // } public TransactionInfo findLastTransactionByCommuterId(int commuter_id) { String query = "from TransactionInfo b where b.commuter_id=? order by created_at desc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getSingleRecord(TransactionInfo.class, query, parameters, 1); } public boolean insertARecharge(TransactionInfo recharge) { recharge.setCreated_at(new Timestamp(new Date().getTime())); return insertEntity(recharge); } // ideally in any case, the users, balance shouldnt be less than // zero.if in any case (due to marketing efforts), if we decide, // then it can be zero. for e.g. Allow users to book a ride, if // he // is short of 10credits, // like needs 30 credits and he have only 20 credits public Integer insertATransaction(TransactionInfo tx) { // last TransactionInfo lastTx = findLastTransactionByCommuterId(tx.getCommuter_id()); Integer points_added = tx.getPoints_added(); Integer points_deduced = tx.getPoints_deducted(); Integer free_rides_added = tx.getFree_rides_added(); Integer free_rides_deduced = tx.getFree_rides_deducted(); // Adjusting credit points (credits) balance if (tx.getTransaction_type() == TransactionType.CREDIT.getTypeCode()) { if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance() + points_added); } else { tx.setPoints_balance(0 + points_added); } } else if (tx.getTransaction_type() == TransactionType.DEBIT.getTypeCode()) { if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance() - points_deduced); } else { tx.setPoints_balance(0 - points_deduced); } } // Adjusting free rides balance. if (tx.getTransaction_type() == TransactionType.CREDIT.getTypeCode()) { System.out.println("lastTx:"+lastTx); if (lastTx != null) { tx.setFree_rides_balance(lastTx.getFree_rides_balance() + free_rides_added); } else { tx.setFree_rides_balance(0 + free_rides_added); } } else if (tx.getTransaction_type() == TransactionType.DEBIT.getTypeCode()) { if (lastTx != null) { tx.setFree_rides_balance(lastTx.getFree_rides_balance() - free_rides_deduced); } else { // TODO: think about it more => I think, this should not be the case, as free rides cant be in negative // but credit can. //tx.setFree_rides_balance(0 - free_rides_deduced); // IDEALLY code(flow) should not reach here. throw new IllegalArgumentException("it seems to be a BUG as its not possible to deduct free rides when user dont have any free rides balance available"); } } //validateTransaction(tx); tx.setTransaction_action(tx.getTransaction_action()); tx.setTransaction_desc(tx.getTransaction_desc()); tx.setCreated_at(new Timestamp(new Date().getTime())); return (Integer) storeInDBAndGetId(tx); } private void validateTransaction(TransactionInfo tx){ if (tx.getFree_rides_added() < 0) { throw new IllegalArgumentException("Free rides added cant be negative"); } if (tx.getFree_rides_deducted() < 0) { throw new IllegalArgumentException("Free rides deducted cant be negative"); } if (tx.getFree_rides_balance() < 0) { throw new IllegalArgumentException("Free rides balance cant be negative"); } } public boolean insertUserPaymentTransactionHistory(Session session, Booking booking) { int commuter_id = booking.getCommuter_id(); int charged_points = booking.getCharged_fare(); int charged_free_rides = booking.getCharged_free_rides(); TransactionStatus txStatus = TransactionStatus.SUCCESS; TransactionBy txBy = TransactionBy.USER; TransactionType txType = TransactionType.DEBIT; // last TransactionInfo lastTx = findLastTransactionByCommuterId(commuter_id); TransactionInfo tx = new TransactionInfo(); tx.setCommuter_id(commuter_id); System.out.println("charing points:"+charged_points); System.out.println("lastTx:"+lastTx); if (lastTx != null) { System.out.println("points balance:" + lastTx.getPoints_balance()); } tx.setPoints_deducted(charged_points); tx.setFree_rides_deducted(charged_free_rides); // Adjusting credit points balance. if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance() - charged_points); } else { // ideally in any case, the users, balance shouldnt be less than // zero.if in any case (due to marketing efforts), if we decide, // then it can be zero. for e.g. Allow users to book a ride, if he // is short of 10credits, // like needs 30 credits and he have only 20 credits tx.setPoints_balance(0 - charged_points); } // Adjusting free rides balance. if (lastTx != null) { System.out.println("charged_free_rides:"+charged_free_rides+"--lastTx.getFree_rides_balance():"+lastTx.getFree_rides_balance()); if (lastTx.getFree_rides_balance() != null) { tx.setFree_rides_balance(lastTx.getFree_rides_balance() - charged_free_rides); } else { // ideally it should never come here. //tx.setFree_rides_balance(0 - charged_free_rides); throw new IllegalArgumentException( "it seems to be a BUG as its not possible to deduct free rides when user dont have any free rides balance available"); } } else { // TODO: think about it more => I think, this should not be the // case, as free rides cant be in negative // but credit can. // tx.setFree_rides_balance(0 - charged_free_rides); // IDEALLY code(flow) should not reach here. throw new IllegalArgumentException( "it seems to be a BUG as its not possible to deduct free rides when user dont have any free rides balance available"); } //validateTransaction(tx); tx.setTransaction_by(txBy.getTypeCode()); tx.setTransaction_status(txStatus.getTypeCode()); tx.setTransaction_type(txType.getTypeCode()); tx.setBooking_id(booking.getId()); //tx.setTransaction_desc("Booking Done:" + booking.getId()); tx.setTransaction_action(TransactionAction.BOOKING.getName()); tx.setTransaction_desc(TransactionAction.BOOKING.getName()); tx.setCreated_at(new Timestamp(new Date().getTime())); return storeInDB(session, tx); } public boolean insertCancelFreeRidesTransactionHistory(Session session, int commuter_id) { TransactionStatus txStatus = TransactionStatus.SUCCESS; TransactionBy txBy = TransactionBy.SYSTEM; TransactionType txType = TransactionType.DEBIT; // last TransactionInfo lastTx = findLastTransactionByCommuterId(commuter_id); TransactionInfo tx = new TransactionInfo(); tx.setCommuter_id(commuter_id); System.out.println("lastTx:" + lastTx); if (lastTx != null) { System.out.println("points balance:" + lastTx.getPoints_balance()); } tx.setPoints_deducted(0); if (lastTx != null) { // deducting all his free rides, so he can be upgraded to a bigger // offer. tx.setFree_rides_deducted(lastTx.getFree_rides_balance()); } // Adjusting credit points balance. -- Giving his the same balance that he was holding. if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance()); } else { tx.setPoints_balance(0); } // Adjusting free rides balance. tx.setFree_rides_balance(0); tx.setTransaction_by(txBy.getTypeCode()); tx.setTransaction_status(txStatus.getTypeCode()); tx.setTransaction_type(txType.getTypeCode()); tx.setBooking_id(-1); tx.setTransaction_action(TransactionAction.UPGRADE_OFFER.getName()); tx.setTransaction_desc("Upgraded to One Month free"); tx.setCreated_at(new Timestamp(new Date().getTime())); return storeInDB(session, tx); } public Serializable insertUserFullRefundTransactionHistory(Session session, Booking booking) { int commuter_id = booking.getCommuter_id(); int charged_points = booking.getCharged_fare(); int charged_free_rides = booking.getCharged_free_rides(); TransactionStatus txStatus = TransactionStatus.SUCCESS; TransactionBy txBy = TransactionBy.USER; TransactionType txType = TransactionType.CREDIT; // last TransactionInfo lastTx = findLastTransactionByCommuterId(commuter_id); // TODO: Add booking_id field in this table. // Take these message from request as well. I mean admin wants to write a message for settlement. TransactionInfo tx = new TransactionInfo(); tx.setCommuter_id(commuter_id); tx.setPoints_added(charged_points); tx.setFree_rides_added(charged_free_rides); if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance() + charged_points); } else { tx.setPoints_balance(0 + charged_points); } if (lastTx != null) { tx.setFree_rides_balance(lastTx.getFree_rides_balance() + charged_free_rides); } else { tx.setFree_rides_balance(0 + charged_free_rides); } //validateTransaction(tx); tx.setTransaction_by(txBy.getTypeCode()); tx.setTransaction_status(txStatus.getTypeCode()); tx.setTransaction_type(txType.getTypeCode()); //tx.setTransaction_desc("Refund history Done:" + booking.getId()); tx.setBooking_id(booking.getId()); tx.setTransaction_action(TransactionAction.REFUND.getName()); tx.setTransaction_desc(TransactionAction.REFUND.getName()); tx.setCreated_at(new Timestamp(new Date().getTime())); Serializable id = storeInDBAndGetId(session, tx); return id; } // TODO: incomplete method public boolean insertUserPartialRefundTransactionHistory(Session session, Booking booking) { int commuter_id = booking.getCommuter_id(); int charged_points = booking.getCharged_fare(); int charged_free_rides = booking.getCharged_free_rides(); TransactionStatus txStatus = TransactionStatus.SUCCESS; TransactionBy txBy = TransactionBy.USER; TransactionType txType = TransactionType.CREDIT; // last TransactionInfo lastTx = findLastTransactionByCommuterId(commuter_id); // TODO: Add booking_id field in this table. // Take these message from request as well. I mean admin wants to write a message for settlement. TransactionInfo tx = new TransactionInfo(); tx.setCommuter_id(commuter_id); tx.setPoints_added(charged_points); if (lastTx != null) { tx.setPoints_balance(lastTx.getPoints_balance() - charged_points); } else { tx.setPoints_balance(0 - charged_points); } if (lastTx != null) { tx.setFree_rides_balance(lastTx.getFree_rides_balance() + charged_free_rides); } else { tx.setFree_rides_balance(0 + charged_free_rides); } validateTransaction(tx); tx.setTransaction_by(txBy.getTypeCode()); tx.setTransaction_status(txStatus.getTypeCode()); tx.setTransaction_type(txType.getTypeCode()); //tx.setTransaction_desc("Refund history Done:" + booking.getId()); tx.setBooking_id(booking.getId()); tx.setTransaction_action(TransactionAction.PARTIAL_REFUND.getName()); tx.setTransaction_desc(TransactionAction.PARTIAL_REFUND.getName()); tx.setCreated_at(new Timestamp(new Date().getTime())); return storeInDB(session, tx); } public boolean storeInDB(Session session, TransactionInfo tx) { Serializable id = storeInDBAndGetId(session, tx); if (id != null) { return true; } else { return false; } } public Serializable storeInDBAndGetId(Session session, TransactionInfo tx) { validateTransaction(tx); Serializable id = session.save(tx); return id; } public Serializable storeInDBAndGetId(TransactionInfo tx) { validateTransaction(tx); Serializable id = (Serializable) insertEntityAndGetId(tx); return id; } public boolean cancelFreeRides(int commuter_id) { synchronized (this) { Session session = null; Transaction tx = null; session = openSession(); boolean status = true; try { tx = session.beginTransaction(); LogUtil.logActivity("Cancelling free rides of ", commuter_id); if (status) { LogUtil.logActivity("Creating a transaction history entry", commuter_id); status = status && this.insertCancelFreeRidesTransactionHistory(session, commuter_id); if (status) { LogUtil.logActivity("Transaction history created success", commuter_id); } else { LogUtil.logActivity("Transaction history created failed", commuter_id); } } if (status) { LogUtil.logActivity("Updating user wallet balance", commuter_id); // status = status && // accountDao.deductCreditsFromCommuterWallet(session, // booking, trip); status = status && accountDao.cancelAllFreeRidesFromCommuterWallet(session, commuter_id); if (status) { LogUtil.logActivity("Updating user wallet balance success", commuter_id); } else { LogUtil.logActivity("Updating user wallet balance failed", commuter_id); } } if (status) { tx.commit(); } else { tx.rollback(); } return status; } catch (HibernateException e) { handleException(e, tx); throw e; } finally { tx = null; closeSession(session); } } } } <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.UsersDao; import com.main.sts.entities.Users; import com.main.sts.util.MD5PassEncryptionClass; @Service public class UserService { @Autowired private MD5PassEncryptionClass encryptionClass; @Autowired private UsersDao usersDao; public List<Users> getAllUsers() { return usersDao.getAllUsers(); } public Users isUserExist(int userid) { return usersDao.getUser(userid); } public void addUser(Users user) { String pass = user.getPassword(); user.setPassword(encryptionClass.EncryptText(pass)); usersDao.insertUser(user); } public Users isUserNameExist(String user_name) { return usersDao.getUser(user_name); } public void updateUser(String full_name,String user_name, String access_status, int user_id) { Users u = isUserExist(user_id); u.setFull_name(full_name); u.setAccess_status(access_status); u.setUser_name(user_name); u.setPassword(u.getPassword()); usersDao.updateUser(u); } public boolean deleteUser(int user_id) { try { Users u = isUserExist(user_id); usersDao.deleteUser(u); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public void changePassword(Users user){ usersDao.updateUser(user); } public Users getUserById(int parseInt) { // TODO Auto-generated method stub return null; } public boolean validatePassword(String rawPass, String hashPass) { String rawPasshashedPassword = encryptionClass.EncryptText(rawPass); // System.out.println(rawPasshashedPassword); if (rawPasshashedPassword.equals(hashPass)) { return true; } else return false; } } <file_sep>package com.main.sts.service; public enum ReturnCodes { // General SUCCESS, MISSING_PARAMETERS, BAD_REQUEST, UNKNOWN_ERROR, // User USER_ALREADY_EXIST, USER_CREATED_SUCCESSFULLY, USER_ALREADY_VERIFIED, USER_VERIFIED, USER_EXIST_OTP_GENERATED, USER_CREATED_OTP_GENERATED, USER_CREATION_FAILED, USER_NOT_EXIST, USER_VERIFICATION_FAILED, USER_OTP_EXPIRED_OTP_GENERATED, USER_ACTIVATED, USER_INVALID_OTP, // Booking BOOKING_SEATS_NOT_AVAILABLE, BOOKING_NOT_ENOUGH_BALANCE, BOOKING_FAILED, BOOKING_SUCCESSFUL, ALREADY_HAVE_MAX_ACTIVE_BOOKINGS, // GCM GCM_REGISTRATION_SUCCESSFUL, GCM_REGISTRATION_FAILED, // Tracking USER_UNREGISTERED_SUCCESSFULLY, USER_UNREGISTRATION_FAILED, VEHICLE_POS_INSERT_SUCCESS, VEHICLE_POS_INSERT_FAILED, USER_POS_INSERT_SUCCESS, USER_POS_INSERT_FAILED, // Transaction TRANSACION_COMPLETED_SUCCESSFULLY, TRANSACION_MANDATORY_PARAMETERS_MISSING, FAILED_TRANSACION_UPDATION_FAILED, TRANSACION_ACCOUNT_UPDATION_FAILED, FAILED_TRANSACION_UPDATION_SUCCESS, // Transaction SUCCESS_TRANSACION_UPDATION_FAILED, TRANSACTION_ADMIN_RECHARGE_UPDATION_FAILED, TRANSACTION_SYSTEM_RECHARGE_UPDATION_FAILED, // Booking BOOKING_CANCELLATION_SUCCESSFUL, BOOKING_CANCELLATION_FAILED, BOOKING_CANCELLATION_NOT_ALLOWED, BOOKING_ALREADY_CANCELLED_FULL_REFUNDED, BOOKING_ALREADY_CANCELLED_NO_REFUND_GIVEN, BOOKING_ALREADY_CANCELLED_PARTIAL_REFUNDED, BOOKING_ID_NOT_EXIST, BOOKING_ALREADY_EXPIRED, // Refund REFUND_FAILED, REFUND_SUCCESS, USER_DETAIL_UPDATION_SUCCESS, USER_DETAIL_UPDATION_FAILED, PAYMENT_TRANSACTION_UPDATION_FAILED, PAYMENT_TRANSACTION_UPDATION_SUCCESS, EC_DEVICE_ID_GENERATED, EC_DEVICE_ID_GENERATION_FAILED, //Save Routes SAVE_ROUTE_ALREADY_EXISTS, SAVE_ROUTE_SUCCESS, SAVE_ROUTE_FAILED, ; public ReturnCodes getReturnCode(String name) { for (ReturnCodes rc : values()) { if (name.equals(rc.name())) { return rc; } } return null; } } <file_sep>$(document).ready(function() { $("table tbody").empty(); $("#loading").show(); load(); setInterval(function() { $("table tbody").empty(); $("#loading").show(); load(); }, 8000); }); function load(){ $.ajax({ url:"homepage/getHomePageData", type:"POST", success:function(result){ //alert(result); result=$.trim(result); var out=result.split("+"); var forNone=out[0].split(":"); //alert(out); if(forNone[0]=="none"){ $("#no_services").show(); $("#loading").hide(); $("#buses_running_outofservice").empty().append(forNone[1]); $("#buses_running_ontime").empty().append(0); $("#buses_running_late").empty().append(0); $("#buses_running_verylate").empty().append(0); } else{ $("#no_services").hide(); //alert(result); for(var i=0;i<out.length;i++){ if(out[i]!=""){ //alert(out[i]); var out_data=out[i].split(","); $("#buses_running_outofservice").empty().append(out_data[8]); $("#buses_running_ontime").empty().append(out_data[9]); $("#buses_running_late").empty().append(out_data[10]); $("#buses_running_verylate").empty().append(out_data[11]); var data= '<tr>'+ '<td><a href="bus_id:'+out_data[0]+'">'+out_data[1]+' </a></td>'+ '<td>'+out_data[2]+' </td>'+ '<td>'+out_data[3]+'</td>'+ '<td>'+out_data[4]+'</td>'+ '<td><a data-toggle="modal" href="driver_id:'+out_data[5]+'#myModal1">'+out_data[6]+' </a></td>'; if(out_data[7]=="ontime"){ data=data+'<td><span class="label label-success">On Time</span></td>'; } if(out_data[7]=="late"){ data=data+'<td><span class="label label-warning">Late</span></td>'; } if(out_data[7]=="verylate"){ data=data+'<td><span class="label label-danger">Very Late</span></td>'; } data=data+'<td><a href="map_id:'+out_data[0]+'"> <i class="icon-map-marker"></i>&nbsp;Map</a></td>'+ '</tr>'; $("table tbody").append(data); $("table tbody a ").click(function(event){ event.preventDefault(); var data=$(this).attr("href").split(":"); if(data[0]=="bus_id"){ window.open('bus?bus_id='+data[1], 'popup_name','height=' + 600 + ',width=' + 900+ ',resizable=no,scrollbars=yes,toolbar=no,menubar=no,location=no'); } if(data[0]=="driver_id"){ } if(data[0]=="map_id"){ window.open('single_map?bus_id='+data[1], 'popup_name','height=' + 600 + ',width=' + 900+ ',resizable=no,scrollbars=yes,toolbar=no,menubar=no,location=no'); } if(data[0]=="driver_id"){ $("#board_time").text(""); $("#exit_time").text(""); var send=data[1].split("#"); $.ajax({ url:"/sts/school_guest/homepage/getdriverinformation", type:"POST", data:"driver_id="+send[0], success:function(result){ if(result=="none"){ $("#board_time").text("none"); $("#exit_time").text("none"); } else{ var data=result.split("+"); $("#board_time").text(data[0]); $("#exit_time").text(data[1]); } } }); } }); } } $("#loading").hide(); } }, error:function(){ } }); } /*var data= '<tr>'+ '<td><a onclick=" openWindow()" href="#">'+o[i].bus_licence+' </a></td>'+ '<td>'+o[i].current_stop+' </td>'+ '<td>'+o[i].arrived_time+'</td>'+ '<td>'+o[i].no_of_students+'</td>'+ '<td>'+o[i].driver_name+'</td>'+ '<td><span class="label label-warning">Late</span></td>'+ '<td><a href="#"> <i class="icon-map-marker"></i>&nbsp;Map</a></td>'+ '</tr>';*/<file_sep>package com.main.sts.dto.response; import java.io.Serializable; public class ReferralDTO implements Serializable { public int id; //public int referred_by; public String code; //public int referral_code_status; //public Timestamp created_at; //public Timestamp updated_at; // this might be coming from differnet service. public String referral_message; public String referral_scheme_desc; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getReferral_message() { return referral_message; } public void setReferral_message(String referral_message) { this.referral_message = referral_message; } public String getReferral_scheme_desc() { return referral_scheme_desc; } public void setReferral_scheme_desc(String referral_scheme_desc) { this.referral_scheme_desc = referral_scheme_desc; } } <file_sep>package com.main.sts.controllers.webapp.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.filter.OncePerRequestFilter; public class SessionCheckSecurityFilter extends OncePerRequestFilter { private String[] ignore = {"login_process", "login", "register", "regenrateOTP", "registerCommuter", "verifyCommuter", "setPassword" }; protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { System.out.println("got request1"); String url = ((HttpServletRequest) req).getRequestURL().toString(); String queryString = ((HttpServletRequest) req).getQueryString(); System.out.println(url + "?" + queryString); String appContext = req.getContextPath(); HttpSession session = req.getSession(false); // ignore if url is for login. otherwise it will block from logging in. if (session != null) { // ignore if these urls should be accessed without user to be // loggedin boolean checkRequired = true; for (String pattern : ignore) { if (url.contains(pattern)) { checkRequired = false; break; } } if (checkRequired) { Object authetication_done = session.getAttribute("authetication_done"); System.out.println("authetication_done:" + authetication_done); if (authetication_done != null) { System.out.println("authetication_done:1"); Object autheticated = session.getAttribute("autheticated"); System.out.println("autheticated:" + autheticated); if (autheticated == null) { res.sendRedirect(appContext + "/login"); return; } } else { System.out.println("authetication_done:2"); res.sendRedirect(appContext + "/login"); return; } } } // final step chain.doFilter(req, res); } }<file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.Stops; import com.main.sts.service.StopsService; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/stop") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class BusStopsController { @Autowired private RolesUtility rolesUtility; public static final Logger logger = Logger.getLogger(BusStopsController.class); @Autowired private StopsService stopservice; @RequestMapping(value = "/stops", method = RequestMethod.GET) public ModelAndView stopsHomePage(ModelAndView model, HttpServletRequest request) { // System.out.println("inside stops controller"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/stops/stops_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); List<Stops> stops = stopservice.getAllStops(); // //System.out.println("stops are "+stops.size()); Collections.sort(stops); /* * List<RouteStopsEntity> rt = rs.getAll(); model.addObject("rt", rt); */ model.addObject("stops", stops); model.addObject("current_page", "stops"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/addstop", method = RequestMethod.GET) public ModelAndView addStop(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/stops/addstop"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "stops"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/addstopaction", method = RequestMethod.POST) public String addStopAction(final Model model, HttpServletRequest request, @ModelAttribute("stop") Stops stop) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addAttribute("date", formatter.format(new Date())); model.addAttribute("login_name", auth.getName()); model.addAttribute("current_page", "stops"); // validation for stop name duplicate starts Stops stopEntity = stopservice.getStopName(stop.getStop_name()); if (stopEntity != null) { model.addAttribute("stop", stop); model.addAttribute("error_message", "stopDup"); return "/school_admin/stops/addstop"; } // validation for stop name duplicate starts // validation for stop latitude and longitude duplicate starts Stops se = stopservice.getStop(stop.getLatitude(), stop.getLongitude()); if (se != null) { model.addAttribute("stop", stop); model.addAttribute("error_message", "latAndLongDup"); return "/school_admin/stops/addstop"; } // validation for stop latitude and longitude duplicate ends else { // stop.setIsAssigned("no"); stopservice.insertStop(stop); logger.info("Stop [ " + stop.getStop_name() + " ] got added"); return "redirect:/school_admin/stop/stops"; } } @RequestMapping(value = "/updatestop", method = RequestMethod.GET) public ModelAndView updateStop(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/stops/updatestop"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "stops"); int stopId = Integer.parseInt(request.getParameter("id")); Stops stopEntity = stopservice.getStop(stopId); model.addObject("stop", stopEntity); session.setAttribute("stopId", stopId); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/updatestopaction", method = RequestMethod.POST) public ModelAndView updateStopAction(ModelAndView model, HttpServletRequest request, HttpSession session, @ModelAttribute Stops stop) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "stops"); int stopId = (Integer) session.getAttribute("stopId"); List<Stops> stopList = stopservice.getAllStops(); String old_isassigned=stopservice.getStop(stopId).getIsAssigned(); if(old_isassigned.equalsIgnoreCase("no")) { stop.setIsAssigned("0"); } else { stop.setIsAssigned(old_isassigned); } for (Stops stopEntity : stopList) { if (!(stopEntity.getId() == (stopId))) { String stopName = stopEntity.getStop_name(); String longitude = stopEntity.getLongitude(); String latitude = stopEntity.getLatitude(); if (stop.getStop_name().equals(stopName)) { model.addObject("error_message", "stopDup"); model.addObject("stop", stop); model.setViewName("/school_admin/stops/updatestop"); return model; } if (stop.getLatitude() == latitude && stop.getLongitude() == longitude) { model.addObject("error_message", "latAndLongDup"); model.addObject("stop", stop); model.setViewName("/school_admin/stops/updatestop"); return model; } } } // System.out.println(stop); stopservice.updateStop(stopId, stop); logger.info("Stop [ " + stop.getStop_name() + " ] got Updated"); return new ModelAndView("redirect:/school_admin/stop/stops"); } @RequestMapping(value = "/deletestop", method = RequestMethod.GET) public ModelAndView removeStop(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "stops"); model.setViewName("/school_admin/stops/removestop"); int stopId = Integer.parseInt(request.getParameter("id")); Stops stopEntity = stopservice.getStop(stopId); HttpSession session = request.getSession(); session.setAttribute("id", stopId); // //System.out.println("stop to delete "+stopEntity); model.addObject("stop", stopEntity); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/deletestopaction", method = RequestMethod.POST) public String removeStopAction(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } HttpSession session = request.getSession(); int stopId = (Integer) session.getAttribute("id"); String stopname = stopservice.getStop(stopId).getStop_name(); stopservice.deleteStop(stopId); logger.info("Stop [ " + stopname + " ] got Deleted"); return "redirect:/school_admin/stop/stops"; } @RequestMapping(value = "/removeAllStopsByStopIds", method = RequestMethod.POST) public @ResponseBody String removeAllStopsByStopIds(ModelAndView model, HttpServletRequest request) { // //System.out.println("inside delete stops method"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String stopIds = request.getParameter("stopIds"); //System.out.println(stopIds); String stopsIdsArray[] = stopIds.split(","); int totalItems = stopsIdsArray.length; //System.out.println(totalItems); Stops stop = null; for (int i = 0; i < totalItems; i++) { // System.out.println("staff to be deleted: "+stopsIdsArray[i-1]); //busStopsDaoImpl.deleteStopByStopId(stopsIdsArray[i]); stop = stopservice.getStop(Integer.parseInt(stopsIdsArray[i])); stopservice.deleteStop(stop); logger.info("Stop [ "+stop.getStop_name()+" ] deleted"); } // return null; return "stops"; } // search function @RequestMapping(value = "/search", method = RequestMethod.POST) public @ResponseBody String searchStop(HttpServletRequest request, Model model, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); String searchOption = request.getParameter("searchOption"); System.out.println("inside controller" + rfid_number +" "+searchOption); List<Stops> searchStops = null; searchStops = stopservice.searchStops(searchOption, rfid_number); // System.out.println("stops search.. "+searchStops); session.setAttribute("searchStops", searchStops); return "/sts/school_admin/stop/stopSearch"; } @RequestMapping(value = "/stopSearch", method = RequestMethod.GET) public ModelAndView stopsSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/stops/stops_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "stops"); @SuppressWarnings("unchecked") List<Stops> searchstops = (List<Stops>) session.getAttribute("searchStops"); // System.out.println(searchstops); model.addObject("stops", searchstops); if (searchstops==null) { model.addObject("stops", stopservice.getAllStops()); model.addObject("error_message", "noMatching"); } return model; } }// class <file_sep>package com.main.sts.dao.sql; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.CorporateReferralCode; import com.main.sts.entities.ReferralCode; @Repository public class ReferralCodeDao extends BaseDao { public List<ReferralCode> findAll() { return getAllRecords(ReferralCode.class); } public boolean insertAReferralCode(ReferralCode referralCode) { return insertEntity(referralCode); } public boolean updateAReferralCode(ReferralCode referralCode) { return updateEntity(referralCode); } public boolean deleteReferralCode(ReferralCode referralCode) { return deleteEntity(referralCode); } public ReferralCode getReferralCodeById(int referral_code_id) { String query = "from ReferralCode b where b.id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, referral_code_id); return getSingleRecord(ReferralCode.class, query, parameters); } public ReferralCode getReferralCodeByCode(String referral_code) { String query = "from ReferralCode b where b.code=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, referral_code); return getSingleRecord(ReferralCode.class, query, parameters); } public ReferralCode getReferralCodeByCommuterId(int commuter_id) { String query = "from ReferralCode b where b.referred_by=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getSingleRecord(ReferralCode.class, query, parameters, 1); } public CorporateReferralCode getCorporateReferralCodeByCode(String referral_code) { String query = "from CorporateReferralCode b where b.code=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, referral_code); return getSingleRecord(CorporateReferralCode.class, query, parameters); } ///=========== All Corporate referral codes public List<CorporateReferralCode> findAllCorporateReferralCodes() { return getAllRecords(CorporateReferralCode.class); } public boolean insertACorporateReferralCode(CorporateReferralCode referralCode) { return insertEntity(referralCode); } public boolean updateACorporateReferralCode(CorporateReferralCode referralCode) { return updateEntity(referralCode); } public boolean deleteCorporateReferralCode(CorporateReferralCode referralCode) { return deleteEntity(referralCode); } public int getCommuterByReferralCode(String referral_code) { String query = "select referred_by from referral_codes where code = '" + referral_code +"'"; return getCountOFRecords(query).intValue(); } }<file_sep>package com.main.sts.common; import com.main.sts.common.CommonConstants.BookingStatus; public interface CommonConstants { // "Hello, thanks for signing up!, your referral code is ESY20X"; // String OTP_MSG = "Hello, thanks for signing up!, your otp code is %s"; String OTP_MSG = "Dear %s, thank you for signing up!, your otp code is %s"; String WELCOME_MSG = "Dear %s, Welcome to EasyCommute. We are excited to have you join us and start a new commute experience. We have already " + "credited %s free rides in your account. Please use \"Suggest Route\" if we are not serving on your route. Refer your friends using \"Refer & Earn\" and earn free rides! Happy EasyCommuting!"; String WELCOME_MSG_ALREADY_REGISTERED = "Dear %s, Welcome to EasyCommute again. We are excited to have you join us and start a new commute experience. Please use \"Suggest Route\" if we are not serving on your route. Refer your friends using \"Refer & Earn\" and earn free rides! Happy EasyCommuting!"; String NOTIFICATION_WELCOME_MSG_TITLE = "Welcome to EasyCommute"; //String NOTIFICATION_WELCOME_MSG_NAME = "Thank you %s for signing up. You will receive a welcome message shortly."; //String NOTIFICATION_WELCOME_MSG = "Thank you for signing up. You will receive a welcome message shortly."; String NOTIFICATION_WELCOME_MSG_NAME = "Thank you %s for signing up. Hope you will enjoy our service. Happy EasyCommuting!"; String NOTIFICATION_WELCOME_MSG = "Thank you for signing up. Hope you will enjoy our service. Happy EasyCommuting!"; String ALERT_MESSAGE = "Emergency Alert! User #name# is in urgent need. Call #gender_type# on #mobile# now."; String ALERT_MESSAGE_USER_BOARDED = "#gender_type2# boarded the vehicle #vehicle_type# #vehicle_number# from #pickup_stop_name# to #dropoff_stop_name# at #pickup_stop_time# with booking id #booking_id#. Driver no. is #driver_no#"; int DEFAULT_SIGNUP_POINTS = 0; int DEFAULT_SIGNUP_FREE_RIDES = 2; int DEFAULT_REFERRAL_FREE_RIDES = 1; // now making it int DEFAULT_REFERRAL_FREE_CREDITS = 30; // now making it int MAX_REFERRAL_FREE_RIDES = 5;// TODO: 5 int NUMBER_REFERRAL_1MONTH_FREE_RIDES = 5;// TODO: 5 int DEFAULT_CANCELLATION_ALLOWED_BEFORE_X_MINS = 30; int DEFAULT_CREDITS_AFTER_MAX_REFERRAL = 10; boolean SIGNUP_CREDIT_PROMOTION_SCHEME_ENABLED = true; public static final String DEFAULT_BOOKING_CONFIRMATION_MESSAGE_FORMAT = "Hi #name#, your booking id for your EasyCommute ride from #pickup_stop_name# to #dropoff_stop_name# with #num_seats# seat(s) is #booking_id#. " + "Bus details: #vehicle_type# No: #vehicle_number#. Ride date: #ride_date# The bus depart from #pickup_stop_name#, #pickup_stop_help_text#" + " at #pickup_stop_time#. If any queries, call us on #customer_care_no#"; public static final String DEFAULT_BOOKING_CANCELLATION_MESSAGE_FORMAT = "Hi #name#, your booking id #booking_id# for your EasyCommute ride from #pickup_stop_name# to #dropoff_stop_name# on #ride_date# is cancelled." + " Your credits will be refunded back as per refund policy. If any queries, call us on #customer_care_no#"; public static final String DEFAULT_SYSTEM_BOOKING_CANCELLATION_MESSAGE_FORMAT = "Hi #name#, your booking id #booking_id# for your EasyCommute ride from #pickup_stop_name# to #dropoff_stop_name# on #ride_date# is cancelled due to operational reasons." + " We sincerely regret for the inconvenience caused to you. Your ride credits will be fully refunded back to you. If any queries, call us on #customer_care_no#"; public static final String DEFAULT_NOTIFY_AVAILABILITY_MESSAGE_FORMAT = "Dear user, Seat(s) is available now from #pickup_stop_name# to #dropoff_stop_name# on #ride_date#. You can book now!. If any queries, call us on #customer_care_no#"; public static final String DEFAULT_RIDE_COMPLETED_MESSAGE_FORMAT = "Hi #name#, thank you for riding with us. Please share your experience and suggestions in feedback section in EasyCommute app (http://bit.ly/EasyCommuteApp). We hope to serve you again soon! If any queries, call us on #customer_care_no#"; public static final String DEFAULT_BUS_REACHING_MESSAGE_FORMAT = "Hi #name#, your bus had left #current_stop_name#. It will be reaching to #pickup_stop_name#, #pickup_stop_help_text# shortly. If any queries, call us on #customer_care_no#"; public static final String DEFAULT_CUSTOMER_CARE_NO = "8099927902"; // public static final String REFERRAL_MESSAGE = "Register EassyCommute app with my code %s and get 2 free rides. Download EasyCommute " // + "https://play.google.com/store/apps/details?id=easy.commute.shuttle.app and enjoy rides."; // public static final String REFERRAL_MESSAGE = "Register in EasyCommute app, Bus Shuttle Service with my code %s and get 1 free ride. Download EasyCommute now at " // + "http://bit.ly/EasyCommuteApp and enjoy free rides."; // public static final String REFERRAL_MESSAGE = "Register in EasyCommute app, Bus Shuttle Service with my code %s and get 1 extra free ride with 2 free rides. Download EasyCommute now at " // + "http://bit.ly/EasyCommuteApp and enjoy free rides."; // public static final String REFERRAL_MESSAGE = "Register in EasyCommute app an AC Bus Shuttle Service with Confirmed Seat, Free Wifi(4G), GPS Tracking starting from 15/-Rs with my code %s and get 1 extra free ride with 2 free rides. Download EasyCommute now from " // + "http://bit.ly/EasyCommuteApp and enjoy free rides."; public static final String REFERRAL_MESSAGE = "Register in EasyCommute app an AC Bus Shuttle Service with Confirmed Seat, Free Wifi(4G), GPS Tracking starting from 15/-Rs with my code %s and get 2 free rides. Download EasyCommute now from " + "http://bit.ly/EasyCommuteApp and enjoy free rides."; public static final String FREE_RIDES_ACC_MESSAGE = "You have %s free ride(s)!"; public static final String FREE_RIDES_ACC_MESSAGE_1MONTH = "You have 2 free ride(s)/day for 1 Month till 10th Jan 2016"; public static final int MAX_ACTIVE_BOOKINGS_ALLOWED_AT_A_TIME = 5; public final static String bus_ontime = "ontime"; public final static String bus_late = "late"; public final static String bus_verylate = "verylate"; public final static String trip_running = "running"; public final static String trip_over = "over"; public final static String PICKUP = "Pick Up"; public final static String DROPOFF = "Drop Off"; public final static int ETA_LATE_TIME = 0; // public final static int ETA_SEND_TIME=5; public final static int STOP_DEVICE_DIFF = 5; public final static int STOPS_WITHIN_RANGE = 5; public final static String ON = "on"; public final static String ETA_MSG = "There is no arrival time available at the moment for this bus." + " Except serious delay. Please contact your school administration for more information."; public final static String subscriber_type_student = "student"; public final static String subscriber_type_staff = "staff"; public final static String subscriber_type_driver = "driver"; public final static int ontime = 5, late = 15; public static enum TransactionType { CREDIT(1), DEBIT(2); int type; private TransactionType(int type) { this.type = type; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static TransactionType getTransactionType(int id) { for (TransactionType bs : values()) { if (bs.type == id) { return bs; } } return null; } } public static enum TransactionStatus { UNKNOWN(-1), SUCCESS(1), FAILED(2); int type; private TransactionStatus(int type) { this.type = type; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static TransactionStatus getTransactionStatus(int id) { for (TransactionStatus bs : values()) { if (bs.type == id) { return bs; } } return null; } } public static enum UserActiveType { ACTIVE(0), BLOCKED(1), SUSPENDED(2); int type; private UserActiveType(int type) { this.type = type; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static UserActiveType getUserActiveType(int id) { for (UserActiveType bs : values()) { if (bs.type == id) { return bs; } } return null; } } public static enum UserStatusType { REGISTED_NOT_ACTIVATED(0), VERIFIED_ACTIVATED(1); int type; private UserStatusType(int type) { this.type = type; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static UserStatusType getUserStatusType(int id) { for (UserStatusType bs : values()) { if (bs.type == id) { return bs; } } return null; } } public static enum TransactionBy { SYSTEM(0), ADMIN(1), USER(2); int type; private TransactionBy(int type) { this.type = type; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static TransactionBy getTransactionBy(int id) { for (TransactionBy bs : values()) { if (bs.type == id) { return bs; } } return null; } } public static enum BookingStatus { RECEIVED(0), ACCEPTED(1), REJECTED(2), CANCELLED_NOREFUND(3), CANCELLED_REFUNDED(4), CANCELLED_PARTIAL_REFUNDED(5), EXPIRED(6), ; private int value; private BookingStatus(int id) { this.value = id; } public int getBookingStatus() { return value; } public int intValue() { return getBookingStatus(); } public static BookingStatus getBookingStatus(int id) { for (BookingStatus bs : values()) { if (bs.value == id) { return bs; } } return null; } } public static enum TransactionAction { RECHARGE(1), BOOKING(2), REFUND(3), PARTIAL_REFUND(4), SYSTEM_RECHARGE(5), UPGRADE_OFFER(6), DEDUCT(7), SYSTEM_DEDUCT(8), EXPIRY(9); private int type; private TransactionAction(int id) { this.type = id; } public int getTypeCode() { return type; } public int intValue() { return getTypeCode(); } public static TransactionAction getTransactionAction(int id) { for (TransactionAction bs : values()) { if (bs.type == id) { return bs; } } return null; } public String getName(){ return name(); } } public static enum ReferralCodeStatus { ACTIVE(0), EXPIRED(1), ; private int type; private ReferralCodeStatus(int id) { this.type = id; } public int getReferralCodeStatus() { return type; } public int intValue() { return getReferralCodeStatus(); } public static ReferralCodeStatus getReferralCodeStatus(int id) { for (ReferralCodeStatus bs : values()) { if (bs.type == id) { return bs; } } return null; } public String getName(){ return name(); } } public static enum TripStatus { NOT_STARTED(0, "not started"), RUNNING(1, "running"), CANCELLED(2, "cancelled"), OVER(3, "over"), STARTING_TRIP(4, "starting"), ENDING_TRIP(5, "ending"), ALREADY_ENDED(6, "already ended"), ; private int value; private String text; private TripStatus(int id, String text) { this.value = id; this.text = text; } public int getStatusValue() { return value; } public int intValue() { return getStatusValue(); } public String getTripStatusText() { return text; } public static TripStatus getTripStatus(int value) { for (TripStatus bs : values()) { if (bs.value == value) { return bs; } } return null; } } //// late,verylate,delay,ontime public static enum VehicleStatus { ONTIME(1, "ontime"), LATE(2, "late"), VERY_LATE(3, "very late"), OUT_OF_SERVICE(4,"outofservice"), DELAY(5, "delayed"),; private int value; private String text; private VehicleStatus(int id, String text) { this.value = id; this.text = text; } public int getStatusValue() { return value; } public int intValue() { return getStatusValue(); } public String getStatusText() { return text; } public static VehicleStatus getVehicleStatus(int value) { for (VehicleStatus bs : values()) { if (bs.value == value) { return bs; } } return null; } public static VehicleStatus getVehicleStatus(String text) { for (VehicleStatus bs : values()) { if (bs.text.equalsIgnoreCase(text)) { return bs; } } return null; } } // //late,verylate,delay,ontime public static enum ReferralOfferType { DAYS(1, "Days"), // like 5 days, so means effective from start Time. TIME_RANGE(2, "Time Range"), // like 29th Dec to 31st Dec ; private int value; private String text; private ReferralOfferType(int id, String text) { this.value = id; this.text = text; } public int getStatusValue() { return value; } public int intValue() { return getStatusValue(); } public String getStatusText() { return text; } public static ReferralOfferType getReferralOfferType(int value) { for (ReferralOfferType bs : values()) { if (bs.value == value) { return bs; } } return null; } public static ReferralOfferType getReferralOfferType(String text) { for (ReferralOfferType bs : values()) { if (bs.text.equalsIgnoreCase(text)) { return bs; } } return null; } } public static enum UserChannelType { MOBILE(1, "Mobile"), WEB(2, "WEB"), ; private int value; private String text; private UserChannelType(int id, String text) { this.value = id; this.text = text; } public int getStatusValue() { return value; } public int intValue() { return getStatusValue(); } public String getStatusText() { return text; } public static UserChannelType getUserChannelType(int value) { for (UserChannelType bs : values()) { if (bs.value == value) { return bs; } } return null; } public static UserChannelType getUserChannelType(String text) { for (UserChannelType bs : values()) { if (bs.text.equalsIgnoreCase(text)) { return bs; } } return null; } } } <file_sep>package com.main.sts.util; public class ErrorCodes { public static final String CODE_1 = "Not able to delete TripDetails, " + "please delete Trips assosiated with this trip first"; } <file_sep>package com.ec.eventserver.controllers; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ec.eventserver.dto.request.DeviceRequest; import com.ec.eventserver.dto.request.DeviceResponse; import com.ec.eventserver.models.DeviceInfo; import com.ec.eventserver.service.DeviceService; import com.main.sts.common.ServiceException; import com.main.sts.common.ServiceException.ErrorType; import com.main.sts.dto.Response; import com.main.sts.service.ReturnCodes; @Controller @RequestMapping("/event/device") public class DeviceController { @Autowired private DeviceService deviceService; static final Logger logger = Logger.getLogger(DeviceController.class); @RequestMapping(value = "/generate_ec_device_id", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> generateDeviceId(@RequestBody DeviceRequest request) { DeviceResponse deviceInfoResp = null; Response resp = new Response(); try { deviceInfoResp = deviceService.insertDeviceInfo(request); if (deviceInfoResp != null) { resp.message = "Device Id generated"; resp.returnCode = ReturnCodes.EC_DEVICE_ID_GENERATED.name(); } else { resp.message = "Insert failed"; resp.returnCode = ReturnCodes.EC_DEVICE_ID_GENERATION_FAILED.name(); } resp.response = deviceInfoResp; System.out.println(resp); System.out.println("--->>" + new ResponseEntity<Response>(resp, HttpStatus.OK)); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.returnCode = ReturnCodes.EC_DEVICE_ID_GENERATION_FAILED.name(); resp.message = e.getMessage(); System.out.println(resp); return new ResponseEntity<Response>(resp, HttpStatus.OK); } } @RequestMapping(value = "/getByECDeviceId/{ec_device_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> getByECDeviceId(@PathVariable String ec_device_id) { DeviceInfo deviceInfo = null; Response resp = new Response(); try { deviceInfo = deviceService.getDeviceInfoByECDeviceId(ec_device_id); if (deviceInfo != null) { resp.response = deviceInfo; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } else { resp.response = null; resp.message = "Device info not available for: " + ec_device_id; resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { e.printStackTrace(); if (e instanceof ServiceException) { ErrorType errorType = ((ServiceException) e).getErrorType(); if (errorType == ErrorType.ILLEGAL_ARGUMENT) { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(resp, HttpStatus.BAD_REQUEST); } else { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); } } return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } @RequestMapping(value = "/getByHWDeviceId/{hw_device_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> getByHWDeviceId(@PathVariable String hw_device_id) { DeviceInfo deviceInfo = null; Response resp = new Response(); try { deviceInfo = deviceService.getDeviceInfoByHWDeviceId(hw_device_id); if (deviceInfo != null) { resp.response = deviceInfo; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } else { resp.response = null; resp.message = "Device info not available for: " + hw_device_id; resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(HttpStatus.BAD_REQUEST); } } catch (Exception e) { e.printStackTrace(); if (e instanceof ServiceException) { ErrorType errorType = ((ServiceException) e).getErrorType(); if (errorType == ErrorType.ILLEGAL_ARGUMENT) { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.BAD_REQUEST.name(); return new ResponseEntity<Response>(resp, HttpStatus.BAD_REQUEST); } else { resp.response = null; resp.message = e.getMessage(); resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); } } return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>/* Generated by JavaFromJSON */ /*http://javafromjson.dashingrocket.com*/ package com.main.sts.dto; public class Duration { @org.codehaus.jackson.annotate.JsonProperty("value") private java.lang.Integer value; public void setValue(java.lang.Integer value) { this.value = value; } public java.lang.Integer getValue() { return value; } @org.codehaus.jackson.annotate.JsonProperty("text") private java.lang.String text; public void setText(java.lang.String text) { this.text = text; } public java.lang.String getText() { return text; } }<file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "drivers") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "drivers") public class Drivers { @Id @GeneratedValue private Integer id; private String driver_id; private String driver_name; private String contact_number; private String rfid_number; private Integer available; // 0 - available , 1 - not available private Integer active; // 0 - available , 1 - not available private String street; private String city; private String state; private String zip; private String country; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDriver_id() { return driver_id; } public void setDriver_id(String driver_id) { this.driver_id = driver_id; } public String getDriver_name() { return driver_name; } public void setDriver_name(String driver_name) { this.driver_name = driver_name; } public String getContact_number() { return contact_number; } public void setContact_number(String contact_number) { this.contact_number = contact_number; } public String getRfid_number() { return rfid_number; } public void setRfid_number(String rfid_number) { this.rfid_number = rfid_number; } public Integer getAvailable() { return available; } public void setAvailable(Integer available) { this.available = available; } public Integer getActive() { return active; } public void setActive(Integer active) { this.active = active; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Drivers [id=" + id + ", driver_id=" + driver_id + ", driver_name=" + driver_name + ", contact_number=" + contact_number + ", rfid_number=" + rfid_number + ", available=" + available + ", active=" + active + ", street=" + street + ", city=" + city + ", state=" + state + ", zip=" + zip + ", country=" + country + "]"; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "payment_transaction") public class PaymentTransaction implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "payment_transaction_seq_gen") @SequenceGenerator(name = "payment_transaction_seq_gen", sequenceName = "payment_transaction_id_seq") private int id; public int commuter_id; // mihpayid=403993715513773344 public String mihpayid; // mode=CC public String mode; // txnid=3ac6706bbcc27316a498 public String txnid; // amount=10.0 public double amount; public String email; public String mobile; // success, or failure public String status; // bank_ref_num=830790561053161 public String bank_ref_num; // bankcode=CC public String bankcode; // error=E000 public String error; // error_Message=No+Error public String error_message; // discount=0.00 public double discount; // net_amount_debit public Integer net_amount_debit; public Date created_at; private String payment_provider = "payumoney"; public String getMihpayid() { return mihpayid; } public void setMihpayid(String mihpayid) { this.mihpayid = mihpayid; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } public String getTxnid() { return txnid; } public void setTxnid(String txnid) { this.txnid = txnid; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getBank_ref_num() { return bank_ref_num; } public void setBank_ref_num(String bank_ref_num) { this.bank_ref_num = bank_ref_num; } public String getBankcode() { return bankcode; } public void setBankcode(String bankcode) { this.bankcode = bankcode; } public String getError() { return error; } public void setError(String error) { this.error = error; } public String getError_message() { return error_message; } public void setError_message(String error_message) { this.error_message = error_message; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public Integer getNet_amount_debit() { return net_amount_debit; } public void setNet_amount_debit(Integer net_amount_debit) { this.net_amount_debit = net_amount_debit; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } } <file_sep>package com.main.sts.controllers; import java.io.File; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.Commuter; import com.main.sts.service.CommuterService; import com.main.sts.service.NotificationService; import com.main.sts.service.SMSService; @Controller @RequestMapping(value = "/school_admin/push_note") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class PushNotificationsController { @Autowired private CommuterService commuterService; @Autowired private NotificationService notificationService; @Autowired private SMSService smsService; @RequestMapping(value = "/create", method = RequestMethod.GET) public ModelAndView getAllStops(ModelAndView model, HttpServletRequest request) { String ApplicationName = ((HttpServletRequest) request).getContextPath().replace("/", ""); System.out.println("<br/>File system context path (in TestServlet): " + ApplicationName); List<Commuter> commuterList = null; try { commuterList = commuterService.findAll(); } catch (Exception e) { e.printStackTrace(); } // Commuter dummyCommuter = new Commuter(); // dummyCommuter.setCommuter_id(-1); // dummyCommuter.setName("all"); // dummyCommuter.setMobile("-1"); // commuterList.add(dummyCommuter); model.setViewName("/school_admin/push_notifications/notes"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("current_page", "push_note"); model.addObject("commuters", commuterList); return model; } @RequestMapping(value = "/send", method = RequestMethod.GET) public ModelAndView send(ModelAndView model, HttpServletRequest request) { System.out.println("Notification send------------------->>>"); try { // String title = request.getParameter("title"); String data = request.getParameter("data"); System.out.println("Notification send------------------->>>" + data); String dataSplit[] = data.split(":"); String ids[] = dataSplit[0].split(","); String title = dataSplit[1].trim(); String message = dataSplit[2].trim(); if (title == null) { throw new IllegalArgumentException("Title cant be null"); } if (message == null) { throw new IllegalArgumentException("Message cant be null"); } for (String id : ids) { notificationService.publishNotification(Integer.parseInt(id), title, message); } } catch (Exception e) { e.printStackTrace(); } model.setViewName("/school_admin/push_notifications/notes"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("current_page", "push_note"); return model; } } <file_sep>package com.main.sts.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.FareDao; import com.main.sts.dao.sql.StopsDao; import com.main.sts.entities.BusFarePriceEntity; import com.main.sts.entities.Stops; @Service("fareService") public class FareService { @Autowired private FareDao fareDao; @Autowired private StopsDao stopsDao; public List<BusFarePriceEntity> findAll() { return fareDao.findAll(); } private BusFarePriceEntity fetchToFare(int source_stop_id, int dest_stop_id) { return fareDao.fetchFare(source_stop_id, dest_stop_id); } public BusFarePriceEntity fetchFare(int source_stop_id, int dest_stop_id) { BusFarePriceEntity entity = this.fetchToFare(source_stop_id, dest_stop_id); // may be we have defined only one type of fare. i mean from JNTU to // Mindspace and Mindspace to JNTU would be same. // Incase they are different, then one entry should be there for each // route. and in that case entity will not be null. if (entity == null) { entity = this.fetchToFare(dest_stop_id, source_stop_id); } // Again trying to find through the sibling_stop_id if (entity == null) { Stops sourceStop = stopsDao.getStop(source_stop_id); Stops destStop = stopsDao.getStop(dest_stop_id); // if source stop is 'D' dropoff then taking its sibling and then trying. if (sourceStop != null && sourceStop.getType()!=null && sourceStop.getType().equals("D")) { int src_id = sourceStop.getSibling_stop_id(); entity = this.fetchToFare(dest_stop_id, src_id); } if (entity == null && destStop != null && destStop.getType() != null && destStop.getType().equals("D")) { int dest_id = destStop.getSibling_stop_id(); entity = this.fetchToFare(source_stop_id, dest_id); } } return entity; } public void insertFare(BusFarePriceEntity e) { if (e.getSource_stop_id() == e.getDest_stop_id()) { throw new IllegalArgumentException("Source and dest stops cant be same"); } fareDao.insertFare(e); } public void updateFare(BusFarePriceEntity e) { fareDao.updateFare(e); } public void deleteFare(BusFarePriceEntity e) { fareDao.deleteFare(e); } public void deleteFare(int fare_id) { BusFarePriceEntity e = fareDao.getFareById(fare_id); fareDao.deleteFare(e); } } <file_sep>package com.main.sts.service; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.android.gcm.server.Result; import com.main.sts.dao.sql.NotificationDao; import com.main.sts.entities.Commuter; import com.main.sts.entities.Notification; import com.main.sts.entities.PushMessage; @Service("notificationService") public class NotificationService { @Autowired private CommuterService commuterService; @Autowired private NotificationDao notificationDao; @Autowired private GoogleGCMService googleGCMService; public List<Notification> findAll() { return notificationDao.findAll(); } public Notification getNoticationById(int notification_id) { String query = "from Notification b where b.id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, notification_id); return notificationDao.getSingleRecord(Notification.class, query, parameters, 1); } public List<Notification> getNoticationByCommuterId(int commuter_id) { String query = "from Notification b where b.commuter_id=? order by created_at desc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return notificationDao.getRecords(Notification.class, query, parameters, 20); } public boolean insertFaq(Notification faq) { return notificationDao.insertANotication(faq); } public boolean publishNotificationToAll(String title, String message) { int offset = 0; int limit = 20; // send until we exhaust all the commuters list in a batch of getting details for 20 persons (limit) while (true) { List<Commuter> commuters = commuterService.findAllActiveAndVerified(offset, limit); if (commuters != null) { for (Commuter commuter : commuters) { try { publishNotification(commuter.getCommuter_id(), commuter.getGcm_reg_id(), title, message); } catch (Exception e) { e.printStackTrace(); } } } else { break; } offset = offset + 10; } return true; } public Notification publishNotification(int commuter_id, String title, String message) { System.out.println("Notification send111------------------->>>"); Commuter commuter = commuterService.getCommuterById(commuter_id); System.out.println("Notification send222------------------->>>"); return publishNotification(commuter_id, commuter.getGcm_reg_id(), title, message); } public Notification publishNotification(int commuter_id, PushMessage pushMessage) { Notification notification = new Notification(); notification.setTitle(pushMessage.getTitle()); notification.setMessage(pushMessage.getMessage()); notification.setCommuter_id(commuter_id); notification.setCreated_at(new Timestamp(new Date().getTime())); // PushMessage pushMessage = new PushMessage(); // pushMessage.setGcm_regid(gcm_reg_id); // pushMessage.setTitle(title); // pushMessage.setMessage(message); System.out.println("Notification send333------------------->>>"); Result result = googleGCMService.sendPushNotification(pushMessage); notification.setMessage_id(result.getMessageId()); boolean status = notificationDao.insertANotication(notification); if (status) { return notification; } else { return null; } } private Notification publishNotification(int commuter_id, String gcm_reg_id, String title, String message) { Notification notification = new Notification(); notification.setTitle(title); notification.setMessage(message); notification.setCommuter_id(commuter_id); notification.setCreated_at(new Timestamp(new Date().getTime())); PushMessage pushMessage = new PushMessage(); pushMessage.setGcm_regid(gcm_reg_id); pushMessage.setTitle(title); pushMessage.setMessage(message); System.out.println("Notification send333------------------->>>"); Result result = googleGCMService.sendPushNotification(pushMessage); notification.setMessage_id(result.getMessageId()); boolean status = notificationDao.insertANotication(notification); if (status) { return notification; } else { return null; } } public boolean updateANotication(int notification_id, String question, String answer) { Notification notification = getNoticationById(notification_id); // notification.setReferral_code_status(notification_status); return notificationDao.updateANotication(notification); } public boolean deleteNotication(int notification_id) { Notification notification = getNoticationById(notification_id); return notificationDao.deleteNotication(notification); } public static void main(String[] args) { System.out.println(Long.toHexString(System.currentTimeMillis())); } } <file_sep>package com.ec.eventserver.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.main.sts.entities.DashboardSettings; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.entities.VehicleGpsData; import com.main.sts.service.DashBoardSettingsService; import com.main.sts.service.RouteStopsService; @Component public class BusStopFinder { @Autowired private DashBoardSettingsService boardSettingsService; @Autowired private RouteStopsService routeStopsService; @Autowired private FindDistance findDistance; @Autowired private SystemProperties systemProperties; public RouteStops find(int route_id, double latitude, double longitude) { double distance_to_find_stop = systemProperties.getDistance_to_find_stop(); List<RouteStops> routeStops = routeStopsService.getAllRouteStops(route_id); double distance = 0.0; RouteStops found_stop = null; for (RouteStops routeStop : routeStops) { distance = findDistance.calculateDistance(latitude, longitude, Double.parseDouble(routeStop.getStop().getLatitude()), Double.parseDouble(routeStop.getStop().getLongitude())); // System.out.println("Busstop " + // routeStop.getStop().getStop_name() + " --> " + distance + "<=" + // distance_to_find_stop); if (distance <= distance_to_find_stop) { found_stop = routeStop; break; } } // System.out.println("Stop found --> " + found_stop); return found_stop; } public boolean isBusAtSchool(Double latitude, Double longitude) { double distance_to_find_stop = systemProperties.getDistance_to_find_stop(); DashboardSettings dashboardSettings = boardSettingsService.getDashBoardSettings(); double distance = findDistance.calculateDistance(latitude, longitude, dashboardSettings.getSchool_latitude(), dashboardSettings.getSchool_longitude()); // System.out.println("BusStopFinder --> dis" + distance); if (distance <= distance_to_find_stop) { return true; } else return false; } public boolean isBusOutOfFirstStop(double latitude, double longitude, String first_stop_latitude, String first_stop_longitude) { return isBusOutOfFirstStop(latitude, longitude, Double.parseDouble(first_stop_latitude), Double.parseDouble(first_stop_longitude)); } public boolean isBusOutOfFirstStop(String latitude, String longitude, String first_stop_latitude, String first_stop_longitude) { return isBusOutOfFirstStop(Double.parseDouble(latitude), Double.parseDouble(longitude), Double.parseDouble(first_stop_latitude), Double.parseDouble(first_stop_longitude)); } public boolean isBusOutOfFirstStop(Double latitude, Double longitude, Double first_stop_latitude, Double first_stop_longitude) { double distance_to_find_stop = systemProperties.getDistance_to_find_stop(); double distance_to_find_bus_outof_stop = systemProperties.getDistance_to_find_bus_outof_stop(); double distance = findDistance.calculateDistance(latitude, longitude, first_stop_latitude, first_stop_longitude); // System.out.println("BusStopFinder --> dis" + distance); if (distance > distance_to_find_stop && distance <= distance_to_find_bus_outof_stop) { return true; } else return false; } public boolean isBusOutOfStop(VehicleGpsData data, Stops stop) { double distance_to_find_stop = systemProperties.getDistance_to_find_stop(); double distance_to_find_bus_outof_stop = systemProperties.getDistance_to_find_bus_outof_stop(); double distance = findDistance.calculateDistance(data.getLatitude(), data.getLongitude(), stop.getLatitude(), stop.getLongitude()); System.out.println(distance); if (distance > distance_to_find_stop && distance <= distance_to_find_bus_outof_stop) { return true; } else return false; } public RouteStops isBusOutOfStop(int route_id, String latitude, String longitude) { return isBusOutOfStop(route_id, Double.parseDouble(latitude), Double.parseDouble(longitude)); } public RouteStops isBusOutOfStop(int route_id, Double latitude, Double longitude) { double distance_to_find_stop = systemProperties.getDistance_to_find_stop(); double distance_to_find_bus_outof_stop = systemProperties.getDistance_to_find_bus_outof_stop(); List<RouteStops> routeStops = routeStopsService.getAllRouteStops(route_id); double distance = 0.0; RouteStops found_stop = null; for (RouteStops routeStop : routeStops) { distance = findDistance.calculateDistance(latitude, longitude, Double.parseDouble(routeStop.getStop().getLatitude()), Double.parseDouble(routeStop.getStop().getLongitude())); // System.out.println("Busstop out --> " + distance); if (distance > distance_to_find_stop && distance <= distance_to_find_bus_outof_stop) { found_stop = routeStop; break; } } return found_stop; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "recharge_options") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "recharge_options") public class RechargeOptions implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "recharge_options_seq_gen") @SequenceGenerator(name = "recharge_options_seq_gen", sequenceName = "recharge_options_id_seq") private int id; private int recharge_amount; private int num_credits_offered; private boolean enabled; private Date created_at; private Date updated_at; // user specific recharges. private Integer commuter_group_id; public int getRecharge_amount() { return recharge_amount; } public void setRecharge_amount(int recharge_amount) { this.recharge_amount = recharge_amount; } public int getNum_credits_offered() { return num_credits_offered; } public void setNum_credits_offered(int num_credits_offered) { this.num_credits_offered = num_credits_offered; } public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public Date getUpdated_at() { return updated_at; } public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; } public Integer getCommuter_group_id() { return commuter_group_id; } public void setCommuter_group_id(Integer commuter_group_id) { this.commuter_group_id = commuter_group_id; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Address; @Repository public class AddressDao extends BaseDao { public void insertAddress(Address address) { insertEntity(address); } public void updateAddress(Address address) { updateEntity(address); } public Address getAddress(int subscriber_id, String subscriber_type) { String query = "from Address b where b.subscriber_id=? and b.subscriber_type=? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, subscriber_id); parameters.put(1, subscriber_type); return getSingleRecord(Address.class, query, parameters); } } <file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "vehicles") public class Vehicles implements Comparable<Vehicles> { @Id @GeneratedValue private int vehicle_id; private String vehicle_licence_number; private String vehicle_capacity; private String vehicle_make_model; private String vehicle_type; private int vehicle_allotted, driverId; @OneToOne(targetEntity = Drivers.class) @JoinColumn(name = "driverId", referencedColumnName = "id", insertable = false, updatable = false) public Drivers driver; public int getVehicle_id() { return vehicle_id; } public String getVehicle_licence_number() { return vehicle_licence_number; } public String getVehicle_capacity() { return vehicle_capacity; } public String getVehicle_make_model() { return vehicle_make_model; } public void setVehicle_id(int vehicle_id) { this.vehicle_id = vehicle_id; } public void setVehicle_licence_number(String vehicle_licence_number) { this.vehicle_licence_number = vehicle_licence_number; } public void setVehicle_capacity(String vehicle_capacity) { this.vehicle_capacity = vehicle_capacity; } public void setVehicle_make_model(String vehicle_make_model) { this.vehicle_make_model = vehicle_make_model; } public int getVehicle_allotted() { return vehicle_allotted; } public void setVehicle_allotted(int vehicle_allotted) { this.vehicle_allotted = vehicle_allotted; } public String getVehicle_type() { return vehicle_type; } public void setVehicle_type(String vehicle_type) { this.vehicle_type = vehicle_type; } @Override public int compareTo(Vehicles o) { return vehicle_licence_number.compareTo(o.getVehicle_licence_number()); } public Drivers getDriver() { return driver; } public void setDriver(Drivers driver) { this.driver = driver; } public int getDriverId() { return driverId; } public void setDriverId(int driverId) { this.driverId = driverId; } @Override public String toString() { return "Buses [vehicle_id=" + vehicle_id + ", vehicle_licence_number=" + vehicle_licence_number + ", vehicle_capacity=" + vehicle_capacity + ", vehicle_make_model=" + vehicle_make_model + ", vehicle_allotted=" + vehicle_allotted + ", driverId=" + driverId + ", driver=" + driver + "]"; } } <file_sep>package com.main.sts; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import com.main.sts.dao.sql.TripDao; import com.main.sts.dao.sql.TripDetailDao; import com.main.sts.entities.TripDetail; import com.main.sts.entities.Trips; public class TripDaoTest extends BaseTest { @Resource private TripDetailDao tripDetailDao; @Resource private TripDao tripDao; @Test public void testGetAllTrips() { List<TripDetail> tripsList = tripDetailDao.getTripDetails();; System.out.println("tripsList:" + tripsList); for (TripDetail trip : tripsList) { System.out.println(trip.getTrip_name() + ":" + trip.getTrip_display_name()); } } @Test public void testSelectedTrip() { String vehicle_number= "AP281234"; int vehicle_id= 740; Date trip_running_date = new Date(); Trips trips = tripDao.getTripByVehicle(vehicle_id, trip_running_date);; System.out.println("tripsList:" + trips); } } <file_sep>package com.main.sts.service; import java.util.ArrayList; import java.util.List; import org.hibernate.service.spi.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.SavedRoutesDao; import com.main.sts.dto.SavedRouteDTO; import com.main.sts.dto.SavedRouteResponse; import com.main.sts.entities.SavedRoutes; import com.main.sts.entities.Stops; @Service("savedRoutesService") public class SavedRoutesService { @Autowired private SavedRoutesDao savedRoutesDao; @Autowired private StopsService stopsService; public List<SavedRoutes> getAllSavedRoutes() { return savedRoutesDao.getAllSavedRoutes(); } public List<SavedRoutes> getAllSavedRoutes(int commuter_id) { List<SavedRoutes> ls = savedRoutesDao.getAllSavedRoutes(commuter_id); return ls; } public List<SavedRouteResponse> getAllSavedRoutesResponse(int commuter_id) { List<SavedRoutes> ls = getAllSavedRoutes(commuter_id); List<SavedRouteResponse> respList = new ArrayList<SavedRouteResponse>(); for (SavedRoutes sr : ls) { SavedRouteResponse resp = new SavedRouteResponse(); resp.setCommuter_id(sr.getCommuter_id()); resp.setFrom_stop_id(sr.getFrom_stop_id()); resp.setTo_stop_id(sr.getTo_stop_id()); resp.setPickup_time_hours(sr.getPickup_time_hours()); resp.setPickup_time_min(sr.getPickup_time_min()); resp.setDropoff_time_hours(sr.getDropoff_time_hours()); resp.setDropoff_time_min(sr.getDropoff_time_min()); Stops from_stop = stopsService.getStop(sr.getFrom_stop_id()); Stops to_stop = stopsService.getStop(sr.getTo_stop_id()); resp.setFrom_stop_name(from_stop.getDisplay_name()); resp.setTo_stop_name(to_stop.getDisplay_name()); resp.setFrom_stop_shortcode(from_stop.getShortcode()); resp.setTo_stop_shortcode(to_stop.getShortcode()); respList.add(resp); } return respList; } public ReturnCodes saveARoute(int commuter_id, int from_stop_id, int to_stop_id, Integer pickup_time_hours, Integer pickup_time_min, Integer dropoff_time_hours, Integer dropoff_time_min) { SavedRoutes existingSR = savedRoutesDao.getSavedRouteForACommuter(commuter_id, from_stop_id, to_stop_id, pickup_time_hours, pickup_time_min, dropoff_time_hours, dropoff_time_min); System.out.println(existingSR); if (existingSR == null) { SavedRoutes sdr = new SavedRoutes(); sdr.setCommuter_id(commuter_id); sdr.setFrom_stop_id(from_stop_id); sdr.setTo_stop_id(to_stop_id); sdr.setPickup_time_hours(pickup_time_hours); sdr.setPickup_time_min(pickup_time_min); sdr.setDropoff_time_hours(dropoff_time_hours); sdr.setDropoff_time_min(dropoff_time_min); boolean result = savedRoutesDao.saveARoute(sdr); if (result) { return ReturnCodes.SAVE_ROUTE_SUCCESS; } else { return ReturnCodes.SAVE_ROUTE_FAILED; } } else { return ReturnCodes.SAVE_ROUTE_ALREADY_EXISTS; } } public ReturnCodes saveARoute(SavedRouteDTO srReq) throws ServiceException { return saveARoute(srReq.getCommuter_id(), srReq.getFrom_stop_id(), srReq.getTo_stop_id(), srReq.getPickup_time_hours(), srReq.getPickup_time_min(), srReq.getDropoff_time_hours(), srReq.getDropoff_time_min()); } } <file_sep>package com.main.sts.controllers.rest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.main.sts.dto.Response; import com.main.sts.dto.SOSDTO; import com.main.sts.service.ReturnCodes; import com.main.sts.service.SOSService; @Controller @RequestMapping("/sos") public class SOSController { static final Logger logger = Logger.getLogger(SOSController.class); @Autowired private SOSService sosService; @RequestMapping(value = "/raise_alert", method = RequestMethod.POST) public @ResponseBody ResponseEntity<Response> raiseAlert(@RequestBody SOSDTO sos) { Response resp = new Response(); try { boolean sendEnabled = true; boolean notified = sosService.raiseAlertForSOSHelp(sos.getCommuter_id(), sendEnabled); if (notified) { resp.setReturnCode(ReturnCodes.SUCCESS.name()); } else { resp.setReturnCode(ReturnCodes.UNKNOWN_ERROR.name()); } resp.response = null; return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.response = null; resp.setReturnCode(ReturnCodes.UNKNOWN_ERROR.name()); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>package com.main.sts.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.common.CommonConstants.VehicleStatus; import com.main.sts.dao.sql.DailyBusNotificationsDao; import com.main.sts.entities.DailyBusNotifications; import com.main.sts.entities.DailyRunningBuses; @Service public class DailyBusNotificationService { @Autowired private DailyBusNotificationsDao dbnDao; public List<DailyBusNotifications> getTodysNotifications(Date running_date, VehicleStatus status) { return dbnDao.getDailyNotification(running_date, status); } public DailyBusNotifications getTodysNotifications(Date running_date, VehicleStatus status, int trip_id) { return dbnDao.getDailyNotification(running_date, status, trip_id); } public void insert(DailyRunningBuses dailyRunningBus, String time, VehicleStatus status) { DailyBusNotifications db = new DailyBusNotifications(); db.setVehicle_id(dailyRunningBus.getVehicle_id()); db.setVehicle_license_number(dailyRunningBus.getVehicle_licence_number()); db.setRunning_date(dailyRunningBus.getRunning_date()); db.setMessage_type("bus_" + status); db.setNotification("Ontime: Bus [ " + dailyRunningBus.getVehicle_licence_number() + " ] is " + status + " at Stop [ " + dailyRunningBus.getCurrent_stop() + " ]"); db.setVehicle_status(status.getStatusValue()); db.setTime(time); db.setTrip_id(dailyRunningBus.getTrip_id()); dbnDao.insertEntity(db); } public void update(DailyBusNotifications busNotifications) { dbnDao.updateEntity(busNotifications); } } <file_sep>package com.main.sts.dao.sql; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; @Repository public class RouteStopsDao extends BaseDao { public void insertRouteStop(RouteStops entity) { insertEntity(entity); } public List<RouteStops> getAllRouteStops() { return getAllRecords(RouteStops.class); } public List<RouteStops> getAllRouteStops(boolean onlyEnabledStops) { String queryStr = null; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); if (onlyEnabledStops) { queryStr = "from RouteStops r where r.enabled = ? AND r.stop.enabled = ? order by r.stop.stop_name asc"; System.out.println("queryStr:" + queryStr); parameters.put(0, onlyEnabledStops); parameters.put(1, true);// adding a check that all the stops should be enabled. other wise dont show. } else { queryStr = "from RouteStops r order by r.stop.stop_name asc"; } return getRecords(RouteStops.class, queryStr, parameters, true); } public List<RouteStops> getAllRouteStopsForRoute(Collection<Integer> selectedRoutes) { String queryStr = "from RouteStops r where r.route_id IN (:ids) order by r.stop.stop_name asc"; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("ids", selectedRoutes); return getRecordsListWithNamedQuery(RouteStops.class, queryStr, parameters, -1, true); } public List<RouteStops> getRouteStops(Integer route_id) { // String queryStr = "from RouteStops r where r.route_id = ? "; // Map<Integer, Object> parameters = new HashMap<Integer, Object>(); // parameters.put(0, route_id); // return getRecords(RouteStops.class, queryStr, parameters); return getRouteStops(route_id, false); } public RouteStops getRouteStopsForAStopId(int route_id, int stop_id) { String queryStr = "from RouteStops r where r.route_id =(:route_id) AND r.stop_id =(:stop_id) "; Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("route_id", route_id); parameters.put("stop_id", stop_id); return getSingleRecordWithNamedQuery(RouteStops.class, queryStr, parameters, true); } public List<RouteStops> getRouteStops(Integer route_id, boolean onlyEnabledRouteStops) { String queryStr = null; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); if (onlyEnabledRouteStops) { queryStr = "from RouteStops r where r.route_id = ? AND r.enabled = ?"; System.out.println("queryStr:"+queryStr); parameters.put(0, route_id); parameters.put(1, onlyEnabledRouteStops); } else { queryStr = "from RouteStops r where r.route_id = ? "; parameters.put(0, route_id); } return getRecords(RouteStops.class, queryStr, parameters, true); } // public List<RouteStops> getAllRouteStops(List[] stop_ids, boolean onlyEnabledStopsInRoute) { // String queryStr = null; // if (onlyEnabledStopsInRoute) { // queryStr = "from RouteStops r where r.stop_id = ? AND r.enabled!='FALSE'"; // } else { // queryStr = "from RouteStops r where r.stop_id = ? "; // } // Map<Integer, Object> parameters = new HashMap<Integer, Object>(); // parameters.put(0, stop_id); // // return getRecords(RouteStops.class, queryStr, parameters); // } public List<RouteStops> getAllRouteStopsForAStop(Integer stop_id, boolean orderedByStopsPosition) { String queryStr = "from RouteStops r where r.stop_id = ? order by stop_number asc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, stop_id); return getRecords(RouteStops.class, queryStr, parameters, true); } public List<RouteStops> getAllEnabledRouteStopsForAStop(Integer stop_id) { String queryStr = "from RouteStops r where r.stop_id = ? AND r.enabled = ? AND r.stop.enabled = ? order by r.stop.stop_name asc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, stop_id); parameters.put(1, true);//r.enabled parameters.put(2, true);//r.stop.enabled return getRecords(RouteStops.class, queryStr, parameters, true); } public RouteStops getRouteStop(Integer id) { String queryStr = "from RouteStops r where r.id = ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return getSingleRecord(RouteStops.class, queryStr, parameters, true); } public RouteStops getRouteStop(int stop_number, Integer route_id) { String queryStr = "from RouteStops r where r.route_id = ? and r.stop_number=? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, route_id); parameters.put(1, stop_number); return getSingleRecord(RouteStops.class, queryStr, parameters, true); } public void incrementStopNumbers(Integer route_id, int stop_number) { String queryStr = "update RouteStops r set r.stop_number = r.stop_number + 1 where r.route_id = ? and r.stop_number > ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, route_id); parameters.put(1, stop_number - 1); // System.out.println(parameters); updateEntitys(RouteStops.class, queryStr, parameters); } public void decrementStopNumbers(Integer route_id, int stop_number) { String queryStr = "update RouteStops r set r.stop_number = r.stop_number - 1 where r.route_id = ? and r.stop_number > ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, route_id); parameters.put(1, stop_number); // System.out.println(parameters); updateEntitys(RouteStops.class, queryStr, parameters); } public void decrementStopNumbersBelow(Integer route_id, int stop_number) { String queryStr = "update RouteStops r set r.stop_number = r.stop_number - 1 where r.route_id = ? and r.stop_number < ? "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, route_id); parameters.put(1, stop_number); // System.out.println(parameters); updateEntitys(RouteStops.class, queryStr, parameters); } public void removeRouteStop(RouteStops routeStop) { deleteEntity(routeStop); } public List<Stops> getStopDetails(int route_id) { String query = "select stops.stop_name,stops.id,stops.latitude,stops.longitude,stops.geofence,stops.isAssigned, stops.enabled, display_name, help_text,image_path, type, tags, sibling_stop_id, shortcode " + "from route_stops_list Inner JOIN stops on route_stops_list.stop_id = stops.id and route_stops_list.route_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, route_id); return getStopsBySqlQuery(Stops.class, query, parameters, true); } // public List<Stops> getAllRouteStopsList() { // String query = // "select stops.stop_name,stops.id,stops.latitude,stops.longitude,stops.geofence,stops.isAssigned, stops.enabled from route_stops_list Inner JOIN stops on route_stops_list.stop_id = stops.id"; // Map<Integer, Object> parameters = new HashMap<Integer, Object>(); // return getStopsBySqlQuery(Stops.class, query, parameters); // } public List<Stops> getAllStopsList() { String query = "select stops.stop_name,stops.id,stops.latitude,stops.longitude,stops.geofence,stops.isAssigned, stops.enabled, stops.tags from stops"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); return getStopsBySqlQuery(Stops.class, query, parameters, true); } } <file_sep>package com.ec.eventserver.service; public class SystemProperties { private int port_number; private String time_zone; private double distance_to_find_stop; private double distance_to_find_bus_outof_stop; private int eta_send_time; private String is_crc_required; private String is_eta_required; private int message_worker_threads; private int message_queue_size; private String response_todevice; public String getResponse_todevice() { return response_todevice; } public void setResponse_todevice(String response_todevice) { this.response_todevice = response_todevice; } public int getMessage_queue_size() { return message_queue_size; } public void setMessage_queue_size(int message_queue_size) { this.message_queue_size = message_queue_size; } public int getMessage_worker_threads() { return message_worker_threads; } public void setMessage_worker_threads(int message_worker_threads) { this.message_worker_threads = message_worker_threads; } public int getEta_send_time() { return eta_send_time; } public void setEta_send_time(int eta_send_time) { this.eta_send_time = eta_send_time; } public int getPort_number() { return port_number; } public void setPort_number(int port_number) { this.port_number = port_number; } public String getTime_zone() { return time_zone; } public void setTime_zone(String time_zone) { this.time_zone = time_zone; } public double getDistance_to_find_stop() { return distance_to_find_stop; } public void setDistance_to_find_stop(double distance_to_find_stop) { this.distance_to_find_stop = distance_to_find_stop; } public double getDistance_to_find_bus_outof_stop() { return distance_to_find_bus_outof_stop; } public void setDistance_to_find_bus_outof_stop(double distance_to_find_bus_outof_stop) { this.distance_to_find_bus_outof_stop = distance_to_find_bus_outof_stop; } public String getIs_crc_required() { return is_crc_required; } public void setIs_crc_required(String is_crc_required) { this.is_crc_required = is_crc_required; } public String getIs_eta_required() { return is_eta_required; } public void setIs_eta_required(String is_eta_required) { this.is_eta_required = is_eta_required; } @Override public String toString() { return "SystemProperties [port_number=" + port_number + ", time_zone=" + time_zone + ", distance_to_find_stop=" + distance_to_find_stop + ", distance_to_find_bus_outof_stop=" + distance_to_find_bus_outof_stop + ", eta_send_time=" + eta_send_time + ", is_crc_required=" + is_crc_required + ", is_eta_required=" + is_eta_required + ", message_worker_threads=" + message_worker_threads + ", message_queue_size=" + message_queue_size + ", response_todevice=" + response_todevice + "]"; } } <file_sep>package com.main.sts.dao; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; //preparing test data dao, so I can query the already existing test_bus_gps_data table to simulate the event tracking @Entity @Table(name = "test_bus_gps_data") public class VehicleGpsTestData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; @Column(name = "device_id") String ec_device_id; @Column(name = "trip_id") Integer trip_id; @Column(name = "lat") String gps_lat; @Column(name = "long") String gps_long; private Timestamp created_at; public String getEc_device_id() { return ec_device_id; } public void setEc_device_id(String ec_device_id) { this.ec_device_id = ec_device_id; } public Integer getTrip_id() { return trip_id; } public void setTrip_id(Integer trip_id) { this.trip_id = trip_id; } public String getGps_lat() { return gps_lat; } public void setGps_lat(String gps_lat) { this.gps_lat = gps_lat; } public String getGps_long() { return gps_long; } public void setGps_long(String gps_long) { this.gps_long = gps_long; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Timestamp getCreated_at() { return created_at; } public void setCreated_at(Timestamp created_at) { this.created_at = created_at; } @Override public String toString() { return "VehicleGpsData [id=" + id + ", vehicle_number=" + ec_device_id + ", trip_id=" + trip_id + ", gps_lat=" + gps_lat + ", gps_long=" + gps_long + ", created_at=" + created_at + "]"; } } <file_sep>port_number=10000 time_zone=india distance_to_find_stop=0.05 distance_to_find_bus_outof_stop=0.1 eta_send_time=5 is_crc_required=no is_eta_required=true message_worker_threads =8 message_queue_size = 8 response_todevice = "$RFID\=0#" <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.StopTypesDao; import com.main.sts.entities.StopType; @Service public class StopTypesService { @Autowired private StopTypesDao stopTypesDao; @Autowired public List<StopType> getAllStopTypes() { return stopTypesDao.getStopTypes(); } public void insertStop(StopType stop_type) { stopTypesDao.insert(stop_type); } public StopType getStopType(int id) { return stopTypesDao.getStopType(id); } public void deleteStop(int id) { StopType stop = getStopType(id); stopTypesDao.deleteStopType(stop); } public void deleteStopType(StopType stop_type) { stopTypesDao.deleteStopType(stop_type); } public StopType getStopTypeByName(String stop_type_name) { return stopTypesDao.getStopTypeByName(stop_type_name); } public void updateStopType(int id, StopType stop_type) { StopType stopType = getStopType(id); stopType.setStop_icon_path(stop_type.getStop_icon_path()); stopType.setStop_type_name(stop_type.getStop_type_name()); stopType.setEnabled(stop_type.getEnabled()); stopTypesDao.updateStopType(stopType); } public void updateStopType(StopType stop_type) { stopTypesDao.updateStopType(stop_type); } public List<StopType> searchStopTypes(String type, String str) { return stopTypesDao.searchStopTypes(str, type); } } <file_sep>package com.main.sts.dao.sql; import java.math.BigInteger; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.springframework.stereotype.Repository; import com.main.sts.common.CommonConstants; import com.main.sts.common.CommonConstants.UserActiveType; import com.main.sts.entities.Commuter; import com.main.sts.entities.SMSCode; import com.main.sts.entities.Trips; @Repository public class CommuterDao extends BaseDao { public BigInteger getCommutersCount() { String query = "select count(id) from commuters"; return this.getCountOFRecords(query); } // PAY ATTENTION BEFORE USING : It will fetch all commuter details in one call. public List<Commuter> findAll() { return getAllRecords(Commuter.class, Order.asc("commuter_id")); } public List<Commuter> findAllLatestFirst() { return getAllRecords(Commuter.class, Order.desc("created_at")); } public List<Commuter> findAllOldestFirst() { return getAllRecords(Commuter.class, Order.asc("commuter_id")); } public List<Commuter> findAll(int offset, int limit) { String query = "from Commuter b "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); return getRecords(Commuter.class, query, parameters, offset, limit, true); } public List<Commuter> findAllActiveAndVerified() { String query = "from Commuter b where b.active=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, CommonConstants.UserActiveType.ACTIVE); return getRecords(Commuter.class, query, parameters, 0, 0, true); } public List<Commuter> findAllActiveAndVerified(int offset, int limit) { String query = "from Commuter b where b.active=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, CommonConstants.UserActiveType.ACTIVE); return getRecords(Commuter.class, query, parameters, offset, limit, true); } public Commuter getCommuter(int commuter_id) { String query = "from Commuter b where b.id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getSingleRecord(Commuter.class, query, parameters, true); } public boolean insertCommuter(Commuter commuter) { commuter.setCreated_at(new Timestamp(new Date().getTime())); return insertEntity(commuter); } public Commuter getCommuterByMobile(String mobileNo) { String query = "from Commuter b where b.mobile=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, mobileNo); return getSingleRecord(Commuter.class, query, parameters, true); } public Commuter getCommuterByEmail(String email) { String query = "from Commuter b where b.email=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, email); return getSingleRecord(Commuter.class, query, parameters, true); } public boolean updateCommuter(Commuter commuter) { commuter.setUpdated_at(new Timestamp(new Date().getTime())); return updateEntity(commuter); } public void enableCommuter(int commuter_id) { changeCommuterStatus(commuter_id, UserActiveType.ACTIVE); } public boolean disableCommuter(int commuter_id) { return changeCommuterStatus(commuter_id, UserActiveType.BLOCKED); } public boolean changeCommuterStatus(int commuter_id, UserActiveType type) { Commuter commuter = getCommuter(commuter_id); commuter.active = type.getTypeCode(); commuter.setUpdated_at(new Timestamp(new Date().getTime())); return updateEntity(commuter); } public boolean deleteCommuter(Commuter commuter) { return deleteEntity(commuter); } public List<Commuter> searchCommuters(String str, String type) { Map<String, Object> restrictions = new HashMap<String, Object>(); restrictions.put(type, "%" + str + "%"); return searchRecords(Commuter.class, restrictions); } public List<Commuter> searchCommuters(String columnName, Integer val) { Map<String, Object> restrictions = new HashMap<String, Object>(); restrictions.put(columnName, val); return searchRecords(Commuter.class, restrictions); } public boolean deleteSMSCode(SMSCode smsCode) { return deleteEntity(smsCode); } public boolean deleteSMSCodeByCommuterId(int commuter_id) { List<SMSCode> smsCodes = getSMSCodeByCommuterId(commuter_id); boolean deleted = true; for (SMSCode smsCode : smsCodes) { System.out.println("deleting entry for smscode id:" + smsCode.getId()); boolean status = deleteSMSCode(smsCode); deleted = deleted && status; } return deleted; } public boolean insertSMSCode(int commuter_id, int otp) { SMSCode smsCode = new SMSCode(); smsCode.setCommuter_id(commuter_id); smsCode.setCode(otp); smsCode.setStatus(0); smsCode.setCreated_at(new Timestamp(new Date().getTime())); boolean status = insertEntity(smsCode); return status; } public List<SMSCode> getSMSCodeByCommuterId(int commuter_id) { String query = "from SMSCode b where b.commuter_id=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); return getRecords(SMSCode.class, query, parameters); } // TODO: Fix this part, as it can result in SQL injection attack. public Commuter activateCommuter(int commuter_id, int otpCode) { String query = "from Commuter c , SMSCode s where s.commuter_id = c.id AND c.id= ? AND s.code = ? order by s.created_at desc "; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); parameters.put(1, otpCode); Object[] arr = getSingleRecord(Object[].class, query, parameters, 1); Commuter commuter = (Commuter) arr[0]; return commuter; } public Object[] getCommuterWithOTPCode(int commuter_id) { String query = "from Commuter c , SMSCode s where s.commuter_id = c.id AND c.id= ? order by s.created_at desc"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, commuter_id); Object[] arr = getSingleRecord(Object[].class, query, parameters, 1); // Commuter commuter = (Commuter) arr[0]; // return commuter; return arr; } public boolean insertSMSCode(SMSCode smsCode) { smsCode.setCreated_at(new Timestamp(new Date().getTime())); return insertEntity(smsCode); } public List<Commuter> getCommutersList(Integer offset, Integer limit) { Order orderby = Order.asc("commuter_id"); return this.getRecordsByPagination(Commuter.class, null, orderby, offset, limit); } } <file_sep>$(document).ready(function() { setInterval(function() { $.ajax({ url:"homepage/getHomePageData", type:"POST", success:function(result){ //alert(result); var o=$.parseJSON(result); for(var i=0;i<o.length;i++){ } }, error:function(){ } }); }, 9000); });<file_sep>package com.main.sts.controllers; import java.math.BigInteger; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.SuggestRoute; import com.main.sts.entities.TripDetail; import com.main.sts.entities.Trips; import com.main.sts.service.TripDetailService; import com.main.sts.service.TripService; import com.main.sts.util.DateUtil; import com.main.sts.util.RolesUtility; import com.main.sts.util.SystemConstants; @Controller @RequestMapping(value = "/school_admin/trip") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class TripsController { private static Logger logger = Logger.getLogger(TripsController.class); @Autowired private TripService tripService; @Autowired private RolesUtility rolesUtility; @Autowired private TripDetailService tripDetailService; @RequestMapping(value = "/trips1", method = RequestMethod.GET) public ModelAndView tripssHomePage(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } Integer offset = (request.getParameter("offset") != null && !request.getParameter("offset").trim().isEmpty()) ? Integer.parseInt(request.getParameter("offset")) : 1; Integer limit = (request.getParameter("limit") != null && !request.getParameter("limit").trim().isEmpty()) ? Integer.parseInt(request.getParameter("limit")) : SystemConstants.recordsPerPage; BigInteger count = tripService.getCountOFRecords(true); List<Trips> trips = tripService.getRecordsByPagination(offset, limit); System.out.println(trips); model.addObject("trips", trips); model.addObject("recordsCount", count); model.addObject("limit", limit); model.addObject("offset", offset); model.addObject("recordsPerPage", SystemConstants.recordsPerPage); model.setViewName("/school_admin/trip/trips_list1"); DateFormat formatter = new SimpleDateFormat("dd-MMy-yyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/addTrip1", method = RequestMethod.GET) public ModelAndView addStop(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } List<TripDetail> tripDetails = tripDetailService.getAllTripDetails(); model.setViewName("/school_admin/trip/addtrip1"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.addObject("tripDetails", tripDetails); // get all buses model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/updateTrip1", method = RequestMethod.GET) public ModelAndView updateTrip(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } Trips trip = tripService.getTrip(Integer.parseInt(request.getParameter("id"))); model.setViewName("/school_admin/trip/updatetrip1"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.addObject("trip", trip); // get all buses model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/cancelTrip1", method = RequestMethod.GET) public ModelAndView cancelTrip(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } boolean cancelExpiredBookingsAlso = true; int trip_id = Integer.parseInt(request.getParameter("id")); boolean cancelled = tripService.cancelTrip(trip_id, cancelExpiredBookingsAlso); System.out.println("cancelled:" + cancelled); Trips trip = tripService.getTrip(trip_id); model.setViewName("/school_admin/trip/updatetrip1"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.addObject("trip", trip); model.addObject("trip_cancellation_status", cancelled); // get all buses model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/updatetripaction1", method = RequestMethod.POST) public String updateTripAction(ModelAndView model, HttpServletRequest request) { Trips trip = tripService.getTrip(Integer.parseInt(request.getParameter("id"))); trip.setEnabled(Boolean.parseBoolean(request.getParameter("enabled"))); trip.setTrip_running_date(DateUtil.converStringToDateObject(request.getParameter("date"))); tripService.updatetrip(Integer.parseInt(request.getParameter("id")), trip); return "redirect:trips1"; } @RequestMapping(value = "/deleteTrip1", method = RequestMethod.GET) public ModelAndView removeTrip(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } Trips trip = tripService.getTrip(Integer.parseInt(request.getParameter("id"))); model.setViewName("/school_admin/trip/removetrip1"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "trips"); model.addObject("trip", trip); // get all buses model.addObject("login_role", rolesUtility.getRole(request)); return model; } @RequestMapping(value = "/deleteaction1", method = RequestMethod.POST) public String removeTripAction(ModelAndView model, HttpServletRequest request) { tripService.deleteTrip(Integer.parseInt(request.getParameter("id"))); return "redirect:trips1"; } @RequestMapping(value = "/addtripaction1", method = RequestMethod.POST) public String addStopAction(ModelAndView model, HttpServletRequest request) { try { Integer trip_detail_id = request.getParameter("trip_detail_id") != null ? Integer.parseInt(request .getParameter("trip_detail_id")) : null; Boolean enabled = Boolean.parseBoolean(request.getParameter("enabled")); if (null != request.getParameter("from") && null != request.getParameter("to")) { Set<Date> dates = DateUtil.dateInterval( DateUtil.converStringToDateObject(request.getParameter("from")), DateUtil.converStringToDateObject(request.getParameter("to"))); Trips trip = null; for (Date date : dates) { trip = new Trips(); trip.setEnabled(enabled); trip.setSeats_filled(0); trip.setTrip_detail_id(trip_detail_id); trip.setTrip_running_date(date); tripService.insert(trip); } } return "redirect:trips1"; } catch (Exception e) { logger.error("Exception: " + e.getMessage()); return "redirect:addTrip1"; } } @RequestMapping(value = "/search", method = RequestMethod.POST) public @ResponseBody String searchTrips(HttpServletRequest request, Model model, HttpSession session) { String searchedValue = request.getParameter("search_trips"); String searchOption = request.getParameter("searchOption"); System.out.println(searchedValue + " " + searchOption); List<Trips> searchTrips = new ArrayList<Trips>(); if (searchOption.equals("trip_name")) { searchTrips = tripService.searchTrips(searchOption, searchedValue); } else if (searchOption.equals("trip_running_date")) { searchTrips = tripService.searchTrips(searchOption, searchedValue); } else if (searchOption.equals("seats_filled")) { searchTrips = tripService.searchTrips(searchOption, Integer.valueOf(searchedValue)); } session.setAttribute("searchTrips", searchTrips); return "/sts/school_admin/trip/searchedTrips"; } @RequestMapping(value = "/searchedTrips", method = RequestMethod.GET) public ModelAndView tripsSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/trip/trips_list1"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "list"); List<Trips> tripsList = (List<Trips>) session.getAttribute("searchTrips"); System.out.println(tripsList); model.addObject("trips", tripsList); if (tripsList == null || tripsList.isEmpty()) { //model.addObject("trips", tripService.getAllTrips()); model.addObject("error_message", "noMatching"); } model.addObject("current_page", "trips"); model.addObject("login_role", rolesUtility.getRole(request)); return model; } } <file_sep>package com.ec.eventserver.service; import java.util.Date; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import com.ec.eventserver.dto.request.VehicleGpsDataRequest; import com.ec.eventserver.models.DailyBusStops; import com.main.sts.common.CommonConstants; import com.main.sts.common.CommonConstants.TripStatus; import com.main.sts.common.CommonConstants.VehicleStatus; import com.main.sts.entities.Buses; import com.main.sts.entities.DailyRunningBuses; import com.main.sts.entities.DailySubscriberData; import com.main.sts.entities.DriverSpeedEntity; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.entities.TripDetail; import com.main.sts.entities.Trips; import com.main.sts.entities.VehicleGpsData; import com.main.sts.service.BusesService; import com.main.sts.service.DailyRunningBusesService; import com.main.sts.service.DailySubscriberDataService; import com.main.sts.service.DriverSpeedService; import com.main.sts.service.DriversService; import com.main.sts.service.RouteService; import com.main.sts.service.RouteStopsService; import com.main.sts.service.StudentsService; import com.main.sts.service.TripService; import com.main.sts.util.SystemConstants; @Component public class GpsDataProcess { private static final Logger logger = Logger.getLogger(GpsDataProcess.class); @Autowired private BusesService vehicleService; @Autowired private RouteService routeService; @Autowired private RouteStopsService routeStopsService; @Autowired private BusStopFinder busStopFinder; @Autowired private DailyBusStopService dailyBusStopService; @Autowired private SystemProperties systemProperties; @Autowired private FindDistance findDistance; @Autowired private DailyRunningBusesService dailyRunningBusesService; @Autowired private DailySubscriberDataService dailySubscriberDataService; @Autowired private StudentsService studentsService; @Autowired private TripService tripService; @Autowired private DriversService driversService; @Autowired private DriverSpeedService driverspeedservice; public void process(VehicleGpsDataRequest data, Trips trip, DailyRunningBuses dailyRunningBuses) { // logger.info("GpsDataProcess ----> in process"); Buses vehicle = data.getVehicle(vehicleService, tripService); boolean is_bus_at_school = busStopFinder.isBusAtSchool(data.getGps_lat(), data.getGps_long()); boolean is_stop_school = false; TripDetail tripDetail = trip.getTripDetail(); FirstAndLastRouteStop firstLastRS = getFirstAndLastStopOfATrip(trip); RouteStops lastRouteStop = firstLastRS.last; RouteStops firstRouteStop = firstLastRS.first; Stops firstStop = firstRouteStop.getStop(); if (is_bus_at_school) { logger.info("Bus [ " + vehicle.getBus_licence_number() + " ] arrived to [ school ] at [ " + data.getCreated_at() + " ]"); // Bus is at school dailyRunningBuses.setArrived_time(data.getEventTimeInHoursMins()); VehicleStatus bus_status = findBusStatus(lastRouteStop.getStop_time(), data, dailyRunningBuses); dailyRunningBuses.setVehicle_status(bus_status.intValue()); dailyRunningBusesService.setBusArrivedToLastStop(dailyRunningBuses); if (tripDetail.getTrip_type().equals(SystemConstants.DROPOFF)) { // find students } if (tripDetail.getTrip_type().equals(SystemConstants.PICKUP)) { if (dailyRunningBuses.isIs_bus_arrived_to_trip_last_stop() == false) { dailyRunningBuses.setIs_bus_arrived_to_trip_last_stop(true); dailyRunningBusesService.setBusArrivedToLastStop(dailyRunningBuses); } } is_stop_school = true; } else { Boolean status = dailyRunningBuses.isIs_bus_out_of_first_stop(); if (status != null && !status && dailyRunningBuses.isIs_bus_arrived_to_trip_last_stop() == true) { // Find Bus out of school boolean is_bus_out_of_first_stop = busStopFinder.isBusOutOfFirstStop(data.getGps_lat(), data.getGps_long(), firstStop.getLatitude(), firstStop.getLongitude() ); if (is_bus_out_of_first_stop) { dailyRunningBuses.setIs_bus_out_of_first_stop(true); dailyRunningBusesService.updateDailyRunningBuses(dailyRunningBuses); } is_stop_school = true; } } if (is_stop_school == false) { RouteStops stop = busStopFinder.find(tripDetail.getRouteid(), data.getGps_lat(), data.getGps_long()); if (stop != null) { // logger.info(stop); DailyBusStops dailyBusStops = dailyBusStopService.getDailyBusStop(trip.getId(), data.getCreated_at(), stop.getId()); if (dailyBusStops == null) { dailyBusStopService.insertDailyBusStop(data, stop, trip.getId()); // find bus status at stop VehicleStatus vehicle_status = findBusStatus(stop, data, dailyRunningBuses); dailyRunningBuses.setVehicle_status(vehicle_status.intValue()); dailyRunningBusesService.setBusArrivedToLastStop(dailyRunningBuses); } } else { stop = busStopFinder.isBusOutOfStop(tripDetail.getRouteid(), data.getGps_lat(), data.getGps_long()); if (stop != null) { DailyBusStops dailyBusStops = dailyBusStopService.getDailyBusStop(trip.getId(), data.getCreated_at(), stop.getId()); if (dailyBusStops != null && dailyBusStops.isIs_stop_out_of_range() == false) { // System.out.println("Bus out of range.."); // Set bus out of stop to TRUE dailyBusStopService.setBusOutOfStop(dailyBusStops.getId()); } } } } } public FirstAndLastRouteStop getFirstAndLastStopOfATrip(Trips trip) { int route_id = trip.getTripDetail().getRouteid(); Set<RouteStops> route_stops = routeStopsService.getAllAvailableFromStops(route_id, new RouteStopsService.StopNumberComparator()); RouteStops lastRouteStop = null; RouteStops firstRouteStop = null; // very crude way of finding a last stop of a route for (RouteStops rs : route_stops) { // setting first stop, only on first iteration. from 2nd iteration it wont be null if (firstRouteStop == null) { firstRouteStop = rs; } // setting last stop in each iteration lastRouteStop = rs; } FirstAndLastRouteStop routeStop = new FirstAndLastRouteStop(); routeStop.first = firstRouteStop; routeStop.last = lastRouteStop; return routeStop; } public VehicleStatus findBusStatus(RouteStops routeStops, VehicleGpsDataRequest data, DailyRunningBuses dailyRunningBuses) { Buses vehicle = data.getVehicle(vehicleService, tripService); logger.info("Bus [ " + vehicle.getBus_licence_number() + " ] arrived to stop [ " + routeStops.getStop().getStop_name() + " ] at [ " + data.getEventTimeInHoursMins() + " ]"); dailyRunningBuses.setCurrent_stop(routeStops.getStop().getStop_name()); dailyRunningBuses.setArrived_time(data.getEventTimeInHoursMins()); dailyRunningBusesService.updateDailyRunningBuses(dailyRunningBuses); return calculateTimeDiff(data.getEventTimeInHoursMins(), routeStops.getStop_time()); } public VehicleStatus findBusStatus(String last_stop_time, VehicleGpsDataRequest data, DailyRunningBuses dailyRunningBuses) { dailyRunningBuses.setCurrent_stop("last_stop"); dailyRunningBuses.setArrived_time(data.getEventTimeInHoursMins()); dailyRunningBusesService.updateDailyRunningBuses(dailyRunningBuses); return calculateTimeDiff(data.getEventTimeInHoursMins(), last_stop_time); } public VehicleStatus calculateTimeDiff(Date event_time, String extected_time) { String current_time = event_time.getHours() + ":" + event_time.getMinutes(); return calculateTimeDiff(current_time, extected_time); } public VehicleStatus calculateTimeDiff(String current_time, String extected_time) { VehicleStatus bus_status = null; int c_time = (Integer.parseInt(current_time.split(":")[0]) * 60) + Integer.parseInt(current_time.split(":")[1]); int e_time = (Integer.parseInt(extected_time.split(":")[0]) * 60) + Integer.parseInt(extected_time.split(":")[1]); int diff = c_time - e_time; if (diff <= CommonConstants.ontime) { bus_status = VehicleStatus.ONTIME;//SystemConstants.bus_ontime; logger.info(" Bus Status : [ On Time ]"); } else if (diff > CommonConstants.ontime && diff <= CommonConstants.late) { bus_status = VehicleStatus.LATE;//SystemConstants.bus_late; logger.info(" Bus Status : [ Late ] by [ " + diff + " ] minuts"); } else { bus_status = VehicleStatus.VERY_LATE;//SystemConstants.bus_verylate; logger.info(" Bus Status : [ very Late ] by [ " + diff + " ] minuts"); } return bus_status; } // method to check over speed boolean status; DriverSpeedEntity des = null; int id = 0; public void checkDriverSpeed(ApplicationContext context, VehicleGpsDataRequest data, Trips tripEntity) { // System.out.println("speed checking starts"); Buses vehicle = data.getVehicle(vehicleService, tripService); String time = data.getEventTimeInHoursMins(); // TODO: fix it int speed = 0;//(int) data.getBus_speed(); // auto dist = distance_on_geoid(p1.latitude, p1.longitude, p2.latitude, p2.longitude); // auto time_s = (p2.timestamp - p1.timestamp) / 1000.0; // double speed_mps = dist / time_s; // double speed_kph = (speed_mps * 3600.0) / 1000.0; // System.out.println("speed is " + speed); des = new DriverSpeedEntity(); Date trip_running_date = data.getCreated_at(); DailyRunningBuses currentRunningBuses = dailyRunningBusesService.getDailyRunningBus(tripEntity.getId(), data.getCreated_at(), TripStatus.RUNNING); // System.out.println(currentRunningBuses); if (currentRunningBuses != null) { String trip_name = tripService.getTrip(currentRunningBuses.getTrip_id()).getTripDetail().getTrip_name(); if (speed >= 80) { if (status == false) { int did = currentRunningBuses.getDriver_id(); String dn = driversService.getDriver(did).getDriver_name(); des.setDriver_name(dn); des.setDriver_id(did); des.setStart_time(time); des.setStart_latitude(data.getGps_lat()); des.setStart_longitude(data.getGps_long()); des.setEnd_time(time); des.setEnd_latitude(data.getGps_lat()); des.setEnd_longitude(data.getGps_long()); des.setHighest_speed(speed); des.setTrip_name(trip_name); des.setBus_licence_number(vehicle.getBus_licence_number()); des.setTrip_running_Date(trip_running_date); driverspeedservice.insertSpeed(des); id = des.getId(); logger.info("inserting over speed into database"); // currentRunningBuses.setDriver_speed_id(des.getId()); this.status = true; } else if (status == true) { logger.info("des " + des); DriverSpeedEntity des1 = driverspeedservice.getdriver(id); if (speed >= des.getHighest_speed()) { des1.setEnd_time(time); des1.setEnd_latitude(data.getGps_lat()); des1.setEnd_longitude(data.getGps_long()); des1.setHighest_speed(speed); System.out.println("new speed set " + des1.getHighest_speed()); driverspeedservice.updateDriverSpeed(des1); System.out.println("updated with higher or equal speed " + speed); logger.info("The bus is updating overspeeding in report, speed of the bus is " + des1.getHighest_speed()); } else { des1.setEnd_time(time); des1.setEnd_latitude(data.getGps_lat()); des1.setEnd_longitude(data.getGps_long()); // des.setHighest_speed(speed); // speedDao.updateDriverSpeed(des.getId(),des.getEnd_time(),des.getEnd_latitude(),des.getEnd_longitude(), // des.getHighest_speed()); driverspeedservice.updateDriverSpeed(des1); System.out.println("updated with lower speed " + speed); logger.info("The bus is updating now in report, speed of the bus is" + speed); } } } else { if (status == true) { this.status = false; // currentRunningBuses.setDriver_speed_id(null); logger.info("bus is running below high speed i.e " + speed); } } } } // double distance_on_geoid(double lat1, double lon1, double lat2, double lon2) { // Convert degrees to radians lat1 = lat1 * Math.PI / 180.0; lon1 = lon1 * Math.PI / 180.0; lat2 = lat2 * Math.PI / 180.0; lon2 = lon2 * Math.PI / 180.0; // radius of earth in metres double r = 6378100; // P double rho1 = r * Math.cos(lat1); double z1 = r * Math.sin(lat1); double x1 = rho1 * Math.cos(lon1); double y1 = rho1 * Math.sin(lon1); // Q double rho2 = r * Math.cos(lat2); double z2 = r * Math.sin(lat2); double x2 = rho2 * Math.cos(lon2); double y2 = rho2 * Math.sin(lon2); // Dot product double dot = (x1 * x2 + y1 * y2 + z1 * z2); double cos_theta = dot / (r * r); double theta = Math.acos(cos_theta); // Distance in Metres return r * theta; } public static class FirstAndLastRouteStop { RouteStops first; RouteStops last; } } <file_sep>$(document).ready(function(){ setInterval(function() { $.ajax({ url:"/sts/school_guest/homepage/getNotifications", type:"POST", success:function(result){ $("#add_notifications").empty(); var obj=JSON.parse(result); //add_notifications for (var i=0;i<obj.length;i++){ //alert(obj[i].message_type); var append= '<li > '+ '<div class="col-left">'; if(obj[i].message_type=="bus_started"){ append=append+'<span class="label label-success"><i class="icon-plus"></i></span>'; } if(obj[i].message_type=="bus_arrived_to_stop"){ append=append+'<span class="label label-info"><i class="icon-envelope"></i></span>'; } if(obj[i].message_type=="bus_arrived"){ append=append+'<span class="label label-info"><i class="icon-envelope"></i></span>'; } if(obj[i].message_type=="bus_verylate"){ append=append+'<span class="label label-danger"><i class="icon-warning-sign"></i></span>'; } if(obj[i].message_type=="bus_late"){ append=append+'<span class="label label-danger"><i class="icon-warning-sign"></i></span>'; } if(obj[i].message_type=="bus_ontime"){ append=append+'<span class="label label-info"><i class="icon-bullhorn"></i></span>'; } append=append+ '</div>'+ '<div class="col-right with-margin">'+ '<span class="message">'+obj[i].notification+'</span>'+ '</div>'+ '</li>'; $("#add_notifications").append(append); } } }); }, 3000); });<file_sep>package com.main.sts.controllers.webapp; import java.util.Enumeration; import java.util.concurrent.TimeUnit; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpSession; //import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSession; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.main.sts.common.CommonConstants.UserChannelType; import com.main.sts.controllers.rest.CommuterController; import com.main.sts.dto.CommuterDTO; import com.main.sts.entities.Commuter; import com.main.sts.service.CommuterService; import com.main.sts.service.ReturnCodes; import com.main.sts.util.MD5PassEncryptionClass; import com.main.sts.util.PasswordEncrypter; @Controller @RequestMapping("/webapp/commuter") public class CommuterWebAppController extends CommonController { @Autowired private CommuterService commuterService; @Autowired private BookingWebAppController bookingWebAppController; static final Logger logger = Logger.getLogger(CommuterController.class); @RequestMapping(value = "/login_directly", method = RequestMethod.GET) public ModelAndView loginDirectly(ModelAndView model, HttpServletRequest request, String mobile, HttpServletResponse response) { return loginProcess(model, request, mobile, response); } @RequestMapping(value = "/login_process", method=RequestMethod.POST) public ModelAndView loginProcess(ModelAndView model, HttpServletRequest request, String mobile, HttpServletResponse response) { //HttpSession session = request.getSession(true); String mobile_Str = request.getParameter("mobile"); String otp_str = request.getParameter("otp"); String password = request.getParameter("password"); String flag = request.getParameter("signin_flag"); String remember_me_str = request.getParameter("remember_me"); // if (mobile_Str == null) { // session = request.getSession(false); // Commuter commuter = getCommuter(request); // mobile_Str = commuterDTO.getMobile(); // otp_str = String.valueOf(commuterDTO.getOtp()); // flag = "otp"; // } System.out.println("mobile_Str:" + mobile_Str + "--password:" + password + "--otp:" + otp_str + "--flag:" + flag + "--remember_me_str:" + remember_me_str); if (isLoggedIn(request)) { return bookingWebAppController.showBookingPage(model, request); } boolean remember_me = false; if (remember_me_str != null) { if (remember_me_str.equals("on")) { remember_me = true; } else { remember_me = false; } } if (mobile_Str == null || mobile_Str.equals("null") || mobile_Str.equals("")) { System.out.println("mobile_Str:"+mobile_Str); System.out.println("returning from1:"); return redirectToLogin("Invalid Mobile Number"); } else { mobile_Str = mobile_Str.trim(); } Integer otp = null; if (otp_str != null) { otp_str = otp_str.trim(); if (otp_str.length() > 0) { otp = Integer.parseInt(otp_str); System.out.println("otp:"+otp); System.out.println("returning from2:"); } else { //return new ModelAndView("login"); otp = null; } } else { //return new ModelAndView("login"); otp = null; } if (mobile_Str.length() != 10) { System.out.println("mobile_Str:"+mobile_Str); System.out.println("returning from3:"); return redirectToLogin("Invalid Mobile Number"); } // both can't be null at a time; if (otp_str == null && password == null) { System.out.println("otp_str:"+otp_str+"---password:"+password); System.out.println("returning from4:"); return redirectToLogin( "Login with OTP or Password"); } if (password != null && password.equals("")) { System.out.println("password:"+password); System.out.println("returning from4:"); return redirectToLogin("Enter Your Password"); } if ((otp_str != null && password != null) && otp_str.equals("null") && password.equals("null")) { System.out.println("otp_str:"+otp_str+"---password:"+password); System.out.println("returning from5:"); return redirectToLogin("Login with OTP or Password"); } if (password != null && (password.length() < 6 || password.length() > 14 )) { System.out.println("password:"+password); System.out.println("returning from:"); return redirectToLogin("Enter Your Password (6 - 14) Characters"); } // if otp str is not null and the length is not greater than zero, then show this error. if (otp_str != null && !(otp_str.length() > 0)) { System.out.println("OTP:" + otp_str); System.out.println("returning from4:"); return redirectToLogin("Invalid OTP"); } boolean validated = false; if (flag != null) { System.out.println("flag:" + flag); System.out.println("returning from6:"); if (flag.equals("otp")) { if (otp == null) { return redirectToLogin("Invalid OTP"); } ReturnCodes rc = commuterService.validateUserByOTP(mobile_Str, otp); if (rc == ReturnCodes.USER_VERIFIED) { validated = true; } else { return redirectToLogin("Invalid OTP"); } } else if (flag.equals("password")) { validated = commuterService.validateUserByPassword(mobile_Str, password); if (validated) { // user is autheniticated. } else { return redirectToLogin("Invalid Credentials!"); } } } else { System.out.println("flag:"+flag); System.out.println("returning from7:"); // it means he is autologging. checkAutoLogging(request, response, mobile_Str, remember_me); } if (validated) { Commuter commuter1 = commuterService.getCommuterByMobile(mobile_Str); System.out.println("creating new session"); this.createNewSession(request); // Setting these attributes for tracking a loggedin user. HttpSession session = super.getSession(request); session.setAttribute("authetication_done", true); session.setAttribute("autheticated", true); System.out.println("Added to existign session:"+session); // updating in session. this.addOrUpdateCommuterObject(request, commuter1); if(commuter1.getPassword() == null || commuter1.getPassword().equals("")) { model.setViewName("/set_password"); return model; } return bookingWebAppController.showBookingPage(model, request); } else { return redirectToLogin("Invalid Credentials!"); // show him error page } } private ModelAndView redirectToLogin(String error_message){ return new ModelAndView("login").addObject("error",error_message); } public void checkAutoLogging(HttpServletRequest request, HttpServletResponse response, String mobile, boolean remember_me){ Commuter commuter = null; HttpSession session = getSession(request); String sesid = session.getId(); try { String ecCookie = (String)session.getAttribute("ecCookie"); if(ecCookie != null) { String[] data=ecCookie.split("@"); System.out.println("cookied received:"+data[0]); int commuter_id = Integer.parseInt(commuterService.base64decode(""+data[0])); commuter = commuterService.getCommuterById(commuter_id); } else { commuter = commuterService.getCommuterByMobile(mobile); } session.setAttribute("commuter", commuter); if(remember_me) { ecCookie = commuterService.base64encode(""+commuter.getCommuter_id()) + "@" + sesid; System.out.println("cookied added:"+ecCookie); Cookie cookie = new Cookie("ece", ecCookie); cookie.setMaxAge(((Long)TimeUnit.DAYS.toMillis(3)).intValue());// 3 days. response.addCookie(cookie); } } catch (Exception e) { e.printStackTrace(); } } @RequestMapping(value = "/my_profile") public ModelAndView showUserProfile(ModelAndView model, HttpServletRequest request) { System.out.println("showing user profile"); Commuter commuter = null; try { Commuter sessionCommuter = getCommuter(request); commuter = commuterService.getCommuterById(sessionCommuter.getCommuter_id()); if (commuter.getPassword() != null) { String hashPassword = PasswordEncrypter.decryptText(commuter.getPassword()); commuter.setPassword(<PASSWORD>); } if (isLoggedIn(request)) { System.out.println("loggedin"); model.addObject("commuter", commuter); model.setViewName("/webapp/my_profile"); return model; } else { System.out.println("login"); return redirectToLogin("System error. Couln't login."); } } catch (Exception e) { e.printStackTrace(); } return redirectToLogin("System error. Couln't login."); } @RequestMapping(value = "/user/profile/update", method = RequestMethod.POST) public ModelAndView updateUserProfile(ModelAndView model, HttpServletRequest request, CommuterDTO commuterDTO) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } String name = request.getParameter("name"); String email = request.getParameter("email"); String mobile = request.getParameter("mobile"); String password = request.getParameter("password"); String cpassword = request.getParameter("cpassword"); if ((password != null && cpassword != null) && !(password.equals(cpassword))) { model.addObject("error", "Passwords Does Not Match!"); model.setViewName("/webapp/my_profile"); return model; } String hashPassword = PasswordEncrypter.encryptText(password); Commuter commuter = super.getCommuter(request); commuterDTO.setCommuter_id(commuter.getCommuter_id()); commuterDTO.setName(name); commuterDTO.setEmail(email); commuterDTO.setMobile(mobile); commuterDTO.setPassword(hash<PASSWORD>); int commuter_id = commuter.getCommuter_id(); boolean updated = commuterService.updateCommuterDetails(commuterDTO); if (updated) { commuter = commuterService.getCommuterById(commuter_id); if (commuter.getPassword() != null) { String originalPassword = PasswordEncrypter.decryptText(commuter.getPassword()); commuter.setPassword(originalPassword); } model.addObject("commuter", commuter); model.addObject("message", "success"); } else { // NOTE: this message is given to user, so be careful model.addObject("commuter", commuterDTO); model.addObject("message", "failure"); } } catch (Exception e) { e.printStackTrace(); // NOTE: this message is given to user, so be careful model.addObject("commuter", commuterDTO); model.addObject("message", "failure"); } model.setViewName("/webapp/my_profile"); return model; } @RequestMapping(value = "/register") public ModelAndView showRegistrationPage(ModelAndView model, HttpServletRequest request) { HttpSession session = request.getSession(); //Creates a new Session model.setViewName("/register"); return model; } @RequestMapping(value = "/registerCommuter", method = RequestMethod.POST) public ModelAndView registerCommuter(ModelAndView model, HttpServletRequest request, HttpSession session, CommuterDTO commuterDTO) { String name = request.getParameter("name"); String email = request.getParameter("email"); String mobile = request.getParameter("mobile"); String gender = request.getParameter("gender"); String gcm_reg_id = ""; String referral_code = ""; if(request.getParameter("referral_code") != null) { referral_code = request.getParameter("referral_code"); } String device_id = ""; boolean sms_send_enabled = true; commuterDTO.setName(name); commuterDTO.setEmail(email); commuterDTO.setMobile(mobile); commuterDTO.setGender(gender); commuterDTO.setGcm_reg_id(gcm_reg_id); commuterDTO.setReferral_code(referral_code); commuterDTO.setDevice_id(device_id); commuterDTO.setSms_send_enabled(sms_send_enabled); session = request.getSession(false); if(session.isNew()) { model.setViewName("/login"); return model; } //session.setAttribute("commuterDTO", commuterDTO); UserChannelType channelType = UserChannelType.WEB; ReturnCodes returnCode = null; try { returnCode = commuterService.registerCommuter(name, email, mobile, gender, gcm_reg_id, referral_code, device_id, channelType, sms_send_enabled); if (returnCode != null) { Commuter commuter = commuterService.getCommuterByMobile(mobile); //resp.response = commuter; model.addObject("commuter", commuter); session.setAttribute("commuter", commuter); } // resp.response = dto; model.addObject("returnCode", returnCode.name()); // TODO: handle the response. } catch (Exception e) { e.printStackTrace(); //resp.response = dto; //resp.returnCode = returnCode.name(); // model.addObject("returnCode", returnCode.name()); return model; } model.setViewName("/verification"); return model; } // it will be called only for new users (those are registering, not the // existing users as that will happen in login_process method itself) @RequestMapping(value = "/verifyCommuter", method = RequestMethod.POST) public ModelAndView verifyCommuter(ModelAndView model, HttpServletRequest request, HttpServletResponse response) { Integer otp = null; String otp_str = request.getParameter("otp"); if (otp_str != null && !(otp_str.equals("") || otp_str.equals("null"))) { otp = Integer.parseInt(request.getParameter("otp")); } System.out.println("otp:"+otp); if (otp == null) { model.addObject("message", "Please enter a valid OTP"); model.setViewName("/verification"); return model; } // HttpSession session = request.getSession(false); // if(session.isNew()) { // model.setViewName("/login"); // return model; // } //CommuterDTO commuterDTO= (CommuterDTO)session.getAttribute("commuterDTO"); //commuterDTO.setOtp(otp); //session.setAttribute("dto", commuterDTO); Commuter commuter = getCommuter(request); ReturnCodes returnCode = ReturnCodes.UNKNOWN_ERROR; try { returnCode = commuterService.verifyCommuter(commuter.getMobile(), otp, true); if (returnCode != null) { commuter = commuterService.getCommuterByMobile(commuter.getMobile()); // resp.response = commuter; System.out.println("Comuter Temp1" + commuter); //session.setAttribute("commuter_temp", commuter); model.addObject("commuter", commuter); } String message = ""; if (returnCode == ReturnCodes.USER_ALREADY_VERIFIED) { message = "Already verified"; } else if (returnCode == ReturnCodes.USER_VERIFIED) { message = "Verification succesfful"; } else if (returnCode == ReturnCodes.USER_VERIFICATION_FAILED) { message = "Verification failed"; } model.addObject("message", message); if(message == "Already verified" || message == "Verification succesfful") { // return loginProcess(model, request, commuterDTO.getMobile(), response); model.setViewName("/set_password"); return model; } else { model.setViewName("/verification"); } model.addObject("returnCode", returnCode.name()); return model; } catch (Exception e) { e.printStackTrace(); model.addObject("returnCode", returnCode.name()); model.setViewName("/verification"); return model; } } @RequestMapping(value = "/regenrateOTP", method = RequestMethod.POST) public ModelAndView regenrateOTP(ModelAndView model, HttpServletRequest request, HttpServletResponse response) { BasicConfigurator.configure(); System.out.println("Got request for regenerate OTP"); //CommuterDTO commuterDTO= (CommuterDTO)session.getAttribute("commuterDTO"); String mobile = request.getParameter("mobile"); // trying to get from session, if still dont have then throw him an error. Commuter commuter = getCommuter(request); if (mobile == null) { mobile = commuter.getMobile(); } System.out.println("mobile:" + mobile); if (mobile == null || mobile.equals("null") || mobile.equals("")) { //mobile = commuterDTO.getMobile(); model.addObject("error", "Mobile number can't be empty"); System.out.println("Mobile no. is empty"); model.setViewName("/verification"); return model; } System.out.println("mobile:"+mobile); boolean status = commuterService.regenrateOTP(mobile); System.out.println("status:"+status); if (status) { model.addObject("message", "OTP generated"); } else { // in real it is not going to work, as we are making ajax call. System.out.println("Informing New User to Register First"); return new ModelAndView("redirect:/login"); } System.out.println("returning 1model"); model.setViewName("/verification"); return model; } @RequestMapping(value = "/setPassword", method = RequestMethod.POST) public ModelAndView setPassword(ModelAndView model, HttpServletRequest request, HttpSession session, HttpServletResponse response) { String password = request.getParameter("password"); String cpassword = request.getParameter("cpassword"); if (password != null && cpassword != null && !(password.equals(cpassword))) { model.addObject("error", "Password and confirm password doesn't match"); return model; } String hashPassword = PasswordEncrypter.encryptText(password); session = request.getSession(false); Enumeration emms = session.getAttributeNames(); while (emms.hasMoreElements()) { System.out.println("Session Attributes : " + emms.nextElement()); } Commuter commuter = getCommuter(request); // commuter.setPassword(password); System.out.println("Commuter: " + commuter); boolean isSetPassword = false; try { isSetPassword = commuterService.updateCommuterPassword(commuter.getCommuter_id(), hashPassword); if (isSetPassword) { // setting these variable here so they can be set and filter wont block the reqeusts from entering. HttpSession session1 = getSession(request); session1.setAttribute("authetication_done", true); session1.setAttribute("autheticated", true); model.addObject("message", "Password Set Successfully"); return loginProcess(model, request, commuter.getMobile(), response); } else { model.addObject("message", "failed"); model.setViewName("/set_password"); return model; } } catch (Exception e) { e.printStackTrace(); model.addObject("message", "failed"); model.setViewName("/set_password"); return model; } } } <file_sep>package com.main.sts.entities; public class VehicleTrackingInfo { } <file_sep>package com.main.sts.dto; public class SavedRouteResponse extends SavedRouteDTO { private String from_stop_name; private String to_stop_name; private String from_stop_shortcode; private String to_stop_shortcode; public String getFrom_stop_name() { return from_stop_name; } public void setFrom_stop_name(String from_stop_name) { this.from_stop_name = from_stop_name; } public String getTo_stop_name() { return to_stop_name; } public void setTo_stop_name(String to_stop_name) { this.to_stop_name = to_stop_name; } public String getFrom_stop_shortcode() { return from_stop_shortcode; } public void setFrom_stop_shortcode(String from_stop_shortcode) { this.from_stop_shortcode = from_stop_shortcode; } public String getTo_stop_shortcode() { return to_stop_shortcode; } public void setTo_stop_shortcode(String to_stop_shortcode) { this.to_stop_shortcode = to_stop_shortcode; } @Override public String toString() { return "SavedRouteResponse [from_stop_name=" + from_stop_name + ", to_stop_name=" + to_stop_name + ", from_stop_shortcode=" + from_stop_shortcode + ", to_stop_shortcode=" + to_stop_shortcode + "]"; } } <file_sep> first_name =0 gr_number = 2 last_name = 1 gender=3 parent_first_name=4 parent_last_name=5 parent_mobile=6 parent_email=7 bus_from_home=8 route_from_home=9 pickup_time=10 stop_from_home=11 bus_from_school=12 route_from_school=13 dropoff_time=14 stop_from_school=15 street=16 city=17 state=18 postal=19 country=20 student_grade=21<file_sep>package com.main.sts.dao.sql; import java.io.Serializable; import java.math.BigInteger; import java.sql.Timestamp; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Order; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Restrictions; import org.hibernate.stat.Statistics; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) @Component public class BaseDao { @Autowired private SessionFactory sessionFactory; // public Session session = null; // public Session openSession() { // Session session = null; // if (session != null && session.isOpen()) // return session; // else // session = sessionFactory.openSession(); // return session; // } public Session openSession() { // Statistics statistics = sessionFactory.getStatistics(); // statistics.setStatisticsEnabled(true); // statistics.logSummary(); Session session = sessionFactory.openSession(); return session; } public <T> List<T> getAllRecords(Class<T> clz) { return getAllRecords(clz, null); } // public Session getCurrentSession() { // Session session = sessionFactory.getCurrentSession(); // return session; // } @SuppressWarnings("unchecked") // @Transactional public <T> List<T> getAllRecords(Class<T> clz, Order... orders) { Session session = null; Transaction tx = null; // Query query=null; // return openSession().createCriteria(clz).list(); try { session = openSession(); // tx = session.beginTransaction(); Criteria c = session.createCriteria(clz); if (orders != null) { for (Order order : orders) { c.addOrder(order); } } List ls = c.list();; // tx.commit(); return ls; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @SuppressWarnings("unchecked") // @Transactional public <T> BigInteger getCountOFRecords(String query) { Session session = null; Transaction tx = null; // Query query=null; // return openSession().createCriteria(clz).list(); try { session = openSession(); // tx = session.beginTransaction(); Object count = session.createSQLQuery(query).uniqueResult(); if(count instanceof Integer) { return BigInteger.valueOf((Integer)count); } return (BigInteger)count; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @Transactional public boolean insertEntity(Object entity) { Session session = null; Transaction tx = null; session = openSession(); try { tx = session.beginTransaction(); session.save(entity); tx.commit(); return true; } catch (HibernateException e) { handleException(e, tx); throw e; } finally { tx = null; closeSession(session); } } @Transactional public Serializable insertEntityAndGetId(Object entity) { Session session = null; Transaction tx = null; session = openSession(); try { tx = session.beginTransaction(); Serializable id = session.save(entity); tx.commit(); return id; } catch (HibernateException e) { handleException(e, tx); throw e; } finally { tx = null; closeSession(session); } } @Transactional public boolean updateEntity(Object entity) { Session session = null; session = openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.merge(entity); tx.commit(); return true; } catch (HibernateException e) { handleException(e, tx); return false; } finally { closeSession(session); } } @Transactional public <T> int updateEntitys(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { Session session = null; Transaction tx = null; Query query = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createQuery(queryStr); for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } System.out.println(query); int rowsAffected = query.executeUpdate(); tx.commit(); return rowsAffected; } catch (HibernateException e) { handleException(e, tx); return -1; } finally { tx = null; closeSession(session); } } @Transactional public <T> int updateEntities(Class<T> clz, String queryStr, Map<String, Object> parameters) { Session session = null; Transaction tx = null; Query query = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createQuery(queryStr); for (String k : parameters.keySet()) { Object value = parameters.get(k); if (value instanceof Integer) { query.setInteger(k, (Integer) value); } else if (value instanceof Long) { query.setLong(k, (Long) value); } else if (value instanceof String) { query.setString(k, (String) value); } else if (value instanceof Double) { query.setDouble(k, (Double) value); } else if (value instanceof Timestamp) { query.setTimestamp(k, (Timestamp) value); } else if (value instanceof Date) { query.setDate(k, (Date) value); } } System.out.println(query); int rowsAffected = query.executeUpdate(); tx.commit(); return rowsAffected; } catch (HibernateException e) { handleException(e, tx); return -1; } finally { tx = null; closeSession(session); } } /** * For external session management. * * @param session * @param clz * @param queryStr * @param parameters * @return */ public <T> int updateEntities(Session session, Class<T> clz, String queryStr, Map<String, Object> parameters) { Query query = null; try { query = session.createQuery(queryStr); for (String k : parameters.keySet()) { Object value = parameters.get(k); if (value instanceof Integer) { query.setInteger(k, (Integer) value); } else if (value instanceof Long) { query.setLong(k, (Long) value); } else if (value instanceof String) { query.setString(k, (String) value); } else if (value instanceof Date) { query.setDate(k, (Date) value); } else if (value instanceof Timestamp) { query.setTimestamp(k, (Timestamp) value); } else if (value instanceof Double) { query.setDouble(k, (Double) value); } } System.out.println(query); int rowsAffected = query.executeUpdate(); return rowsAffected; } catch (HibernateException e) { throw e; } finally { } } @Transactional public boolean deleteEntity(Object entity) { Session session = null; session = openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.delete(entity); tx.commit(); return true; } catch (HibernateException e) { handleException(e, tx); throw e; } finally { closeSession(session); tx = null; } } @Transactional public <T> T getSingleRecord(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { return getSingleRecord(clz, queryStr, parameters, -1); } @SuppressWarnings("unchecked") @Transactional public <T> T getSingleRecord(Class<T> clz, String queryStr, Map<Integer, Object> parameters, boolean cacheEnabled) { return getSingleRecord(clz, queryStr, parameters, -1, cacheEnabled); } public <T> T getSingleRecord(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int maxResults) { return getSingleRecord(clz, queryStr, parameters, maxResults, false); } public <T> T getSingleRecord(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int maxResults, boolean cacheEnabled) { Session session = null; Transaction tx = null; Query query = null; try { // BaseDao.session=openSession(); session = openSession(); tx = session.beginTransaction(); query = session.createQuery(queryStr); for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } if (maxResults > 0) { query.setMaxResults(maxResults); } if (cacheEnabled) { query.setCacheable(true); } T obj = (T) query.uniqueResult(); tx.commit(); return obj; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; // this.tx=session.beginTransaction(); // deleteIdleConnections("SELECT pg_terminate_backend(pid) FROM // pg_stat_activity WHERE pid <> pg_backend_pid()AND state = 'idle' // AND datname = 'sts_canada'"); closeSession(session); } } @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int maxResults) { return getRecords(clz, queryStr, parameters, maxResults, false); } @SuppressWarnings("unchecked") @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int maxResults, boolean cacheEnabled) { Session session = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); Query query = session.createQuery(queryStr); if (parameters != null) { for (Integer k : parameters.keySet()) { Object val = parameters.get(k); query.setParameter(k, val); } } if (maxResults != 0) { query.setMaxResults(maxResults); } if (cacheEnabled) { query.setCacheable(true); } List<T> results = (List<T>) query.list(); tx.commit(); return results; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } public <T> T getSingleRecordWithNamedQuery(Class<T> clz, String queryStr, Map<String, Object> parameters, boolean cacheEnabled) { List<T> ls = getRecordsListWithNamedQuery(clz, queryStr, parameters, 1, cacheEnabled); if (ls != null && ls.size() > 0) { return ls.get(0); } else { return null; } } public <T> List<T> getRecordsListWithNamedQuery(Class<T> clz, String queryStr, Map<String, Object> parameters, int maxResults) { return getRecordsListWithNamedQuery(clz, queryStr, parameters, maxResults, false); } /** * Only works with Named query parameter. like * * Query query = session.createQuery("FROM Cat c WHERE c.id IN (:ids)"); * query.setParameterList("ids", listOfIds); OR query.setParameter("ids", * listOfIds); * * @param clz * @param queryStr * @param parameters * @param maxResults * @return */ @SuppressWarnings("unchecked") @Transactional public <T> List<T> getRecordsListWithNamedQuery(Class<T> clz, String queryStr, Map<String, Object> parameters, int maxResults, boolean cacheEnabled) { Session session = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); Query query = session.createQuery(queryStr); for (String k : parameters.keySet()) { Object val = parameters.get(k); if (val instanceof Collection) { query.setParameterList(k, (Collection) val); } else { query.setParameter(k, val); } } // if (maxResults != 0) { if (maxResults > 0) { query.setMaxResults(maxResults); } if (cacheEnabled) { query.setCacheable(true); } List<T> results = (List<T>) query.list(); tx.commit(); return results; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int offset, int maxResults) { return getRecords(clz, queryStr, parameters, offset, maxResults, false); } @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters, int offset, int maxResults, boolean cacheEnabled) { Session session = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); Query query = session.createQuery(queryStr); if (parameters != null) { for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } } if (offset != 0) { query.setFirstResult(offset); // query.setFirstResult((pageNo * maxResults) + 1); } if (maxResults != 0) { query.setMaxResults(maxResults); } if (cacheEnabled) { query.setCacheable(true); } List<T> results = (List<T>) query.list(); tx.commit(); return results; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @SuppressWarnings("unchecked") @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { return getRecords(clz, queryStr, parameters, -1); } @SuppressWarnings("unchecked") @Transactional public <T> List<T> getRecords(Class<T> clz, String queryStr, Map<Integer, Object> parameters, boolean cacheEnabled) { return getRecords(clz, queryStr, parameters, -1, cacheEnabled); } @SuppressWarnings({"unchecked"}) @Transactional public <T> List<T> searchRecords(Class<T> clz, Map<String, Object> restrictions) { Session session = openSession(); Transaction tx = session.beginTransaction(); Criteria c = null; try { c = session.createCriteria(clz); for (String k : restrictions.keySet()) { if (restrictions.get(k) instanceof String) { c.add(Restrictions.ilike(k, restrictions.get(k))); } else if (restrictions.get(k) instanceof Integer) { c.add(Restrictions.eq(k, restrictions.get(k))); } } // System.out.println(c); List<T> list = c.list(); tx.commit(); return list; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @SuppressWarnings("unchecked") public <T> List<T> executeSQLQuery(String queryStr, boolean cacheEnabled) { Session session = null; SQLQuery query = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createSQLQuery(queryStr); if (cacheEnabled) { query.setCacheable(true); } System.out.println("query string:"+query.getQueryString()); List<T> list = query.list(); tx.commit(); return (List<T>) list; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } public <T> List<T> getStopsBySqlQuery(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { return getStopsBySqlQuery(clz, queryStr, parameters, false); } @SuppressWarnings("unchecked") @Transactional public <T> List<T> getStopsBySqlQuery(Class<T> clz, String queryStr, Map<Integer, Object> parameters, boolean cacheEnabled) { Session session = null; SQLQuery query = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createSQLQuery(queryStr); if (parameters != null) { for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } } query.addEntity(clz); if (cacheEnabled) { query.setCacheable(true); } System.out.println("query string:"+query.getQueryString()); List<T> list = query.list(); tx.commit(); return (List<T>) list; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } @SuppressWarnings("unchecked") @Transactional public <T> T getStudentsBySqlQuery(Class<T> clz, String queryStr, Map<Integer, Object> parameters) { Session session = null; SQLQuery query = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createSQLQuery(queryStr); for (Integer k : parameters.keySet()) { query.setParameter(k, parameters.get(k)); } query.addEntity(clz); T entity = (T) query.uniqueResult(); tx.commit(); return entity; } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } public void handleException(Exception e, Transaction tx) { e.printStackTrace(); if (tx != null && tx.isActive()) { tx.rollback(); } } // @Transactional protected void closeSession(Session session) { if (session != null && session.isOpen()) { try { session.close(); } catch (Exception e) { System.out.println("Error while closing the session"); e.printStackTrace(); } } } private void deleteIdleConnections(String queryStr) { Session session = null; SQLQuery query = null; Transaction tx = null; try { session = openSession(); tx = session.beginTransaction(); query = session.createSQLQuery(queryStr); System.out.println("called"); List result = query.list(); tx.commit(); System.out.println("committed " + result); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { tx = null; closeSession(session); } } public <T> List<T> getRecordsByPagination(Class<T> clz, Integer first, Integer count) { return getRecordsByPagination(clz, (Criterion[]) null, null, null, first, count); } public <T> List<T> getRecordsByPagination(Class<T> clz, Criterion crit, Order order, Integer first, Integer count) { return getRecordsByPagination(clz, new Criterion[]{crit}, null, new Order[]{order}, first, count); } public <T> List<T> getRecordsByPagination(Class<T> clz, Criterion crit, Order[] orders, Integer first, Integer count) { return getRecordsByPagination(clz, new Criterion[]{crit}, null, orders, first, count); } public <T> List<T> getRecordsByPagination(Class<T> clz, Criterion[] crits, Projection projection, Order[] orders, Integer first, Integer count) { return getRecordsByPaginationWithOrder(clz, crits, null, orders, first, count); } @SuppressWarnings("unchecked") // @Transactional public <T> List<T> getRecordsByPaginationWithOrder(Class<T> clz, Criterion[] crits, Projection projection, Order[] orders, Integer first, Integer count) { Session session = null; Transaction tx = null; // Query query=null; // return openSession().createCriteria(clz).list(); try { session = openSession(); // tx = session.beginTransaction(); Criteria criteria = session.createCriteria(clz); if (crits != null) { for (Criterion criterion : crits) { if (criterion != null) { criteria.add(criterion); } } } if (orders != null) { for (Order order : orders) { if (order != null) { criteria.addOrder(order); } } } if (first != null) { criteria.setFirstResult(first - 1); } if (count != null) { criteria.setMaxResults(count); } return criteria.list(); } catch (HibernateException e) { handleException(e, tx); return null; } finally { tx = null; closeSession(session); } } } <file_sep>package com.main.sts; import junit.framework.Assert; import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate4.SessionFactoryUtils; import org.springframework.orm.hibernate4.SessionHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * * @author ajaidka * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-security.xml"}) //@ContextConfiguration(locations = {"classpath:servlet-context.xml"}) @WebAppConfiguration public class BaseTest { @Ignore @Test public void testDummy() { Assert.assertNull(null); } @Autowired private SessionFactory sessionFactory; @Before public void setUp() throws Exception { TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(sessionFactory.openSession())); } @After public void tearDown() throws Exception { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSession(sessionHolder.getSession()); } }<file_sep>package com.main.sts.dto; import java.io.Serializable; public class TripDTO implements Serializable { private static final long serialVersionUID = 1L; private int from_stop_id; private int to_stop_id; private String from_stop_code; private String to_stop_code; public int getFrom_stop_id() { return from_stop_id; } public void setFrom_stop_id(int from_stop_id) { this.from_stop_id = from_stop_id; } public int getTo_stop_id() { return to_stop_id; } public void setTo_stop_id(int to_stop_id) { this.to_stop_id = to_stop_id; } public String getFrom_stop_code() { return from_stop_code; } public void setFrom_stop_code(String from_stop_code) { this.from_stop_code = from_stop_code; } public String getTo_stop_code() { return to_stop_code; } public void setTo_stop_code(String to_stop_code) { this.to_stop_code = to_stop_code; } } <file_sep>package com.main.sts.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "stop_types") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "stop_types") public class StopType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "stop_types_id_seq_gen") @SequenceGenerator(name = "stop_types_id_seq_gen", sequenceName = "stop_types_id_seq") private Integer id; private String stop_type_name; private String stop_icon_path; private Boolean enabled; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStop_type_name() { return stop_type_name; } public void setStop_type_name(String stop_type_name) { this.stop_type_name = stop_type_name; } public String getStop_icon_path() { return stop_icon_path; } public void setStop_icon_path(String stop_icon_path) { this.stop_icon_path = stop_icon_path; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } } <file_sep>package com.main.sts.entities; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Entity; @Entity @Table(name="guardians") public class Guardians implements Comparable<Guardians> { @Id @GeneratedValue int id; String first_name,last_name,relation,mobile_number,email; int student_id; int sms_alert_id,email_alert_id; @OneToOne(targetEntity=Alerts.class) @JoinColumn(name="sms_alert_id",referencedColumnName="id",insertable=false,updatable=false) public Alerts sms_alert; @OneToOne(targetEntity=Alerts.class) @JoinColumn(name="email_alert_id",referencedColumnName="id",insertable=false,updatable=false) public Alerts email_alert; public int getId() { return id; } public String getFirst_name() { return first_name; } public String getLast_name() { return last_name; } public String getRelation() { return relation; } public String getMobile_number() { return mobile_number; } public String getEmail() { return email; } public int getStudent_id() { return student_id; } public void setId(int id) { this.id = id; } public void setFirst_name(String first_name) { this.first_name = first_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public void setRelation(String relation) { this.relation = relation; } public void setMobile_number(String mobile_number) { this.mobile_number = mobile_number; } public void setEmail(String email) { this.email = email; } public void setStudent_id(int student_id) { this.student_id = student_id; } @Override public String toString() { return "Guardians [id=" + id + ", first_name=" + first_name + ", last_name=" + last_name + ", relation=" + relation + ", mobile_number=" + mobile_number + ", email=" + email + ", student_id=" + student_id + "]"; } @Override public int compareTo(Guardians o) { return (this.first_name.compareTo(o.first_name)); } public int getSms_alert_id() { return sms_alert_id; } public int getEmail_alert_id() { return email_alert_id; } public Alerts getSms_alert() { return sms_alert; } public Alerts getEmail_alert() { return email_alert; } public void setSms_alert_id(int sms_alert_id) { this.sms_alert_id = sms_alert_id; } public void setEmail_alert_id(int email_alert_id) { this.email_alert_id = email_alert_id; } public void setSms_alert(Alerts sms_alert) { this.sms_alert = sms_alert; } public void setEmail_alert(Alerts email_alert) { this.email_alert = email_alert; } } <file_sep>package com.main.sts.util; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.main.sts.entities.Address; import com.main.sts.entities.Alerts; import com.main.sts.entities.Guardians; import com.main.sts.entities.Parents; import com.main.sts.entities.Staff; import com.main.sts.entities.Students; import com.main.sts.entities.Transport; import com.main.sts.service.StaffService; @Component public class MakeObjects { @Autowired private StaffService staffservice; public Transport getTransport(HttpServletRequest request, int id, String subscriber_type, String transport_type) { Transport transport = new Transport(); transport.setTransport_type(transport_type); transport.setSubscriber_id(id); transport.setSubscriber_type(subscriber_type); // System.out.println("-->" + // request.getParameter("bus_id_number_fromhome").length()); if (transport_type.equals(SystemConstants.PICKUP)) { if (request.getParameter("bus_id_number_fromhome").length() != 0) { transport.setBus_id(Integer.parseInt(request.getParameter("bus_id_number_fromhome"))); transport.setRoute_id(Integer.parseInt(request.getParameter("route_id_fromhome"))); transport.setStop_id(Integer.parseInt(request.getParameter("stop_id_fromhome"))); transport.setTrip_id(Integer.parseInt(request.getParameter("trip_id_fromhome"))); } else { transport.setBus_id(0); transport.setRoute_id(0); transport.setStop_id(0); transport.setTrip_id(0); } } if (transport_type.equals(SystemConstants.DROPOFF)) { if (request.getParameter("bus_id_number_fromschool").length() != 0) { transport.setBus_id(Integer.parseInt(request.getParameter("bus_id_number_fromschool"))); transport.setRoute_id(Integer.parseInt(request.getParameter("route_id_fromschool"))); transport.setStop_id(Integer.parseInt(request.getParameter("stop_id_fromschool"))); transport.setTrip_id(Integer.parseInt(request.getParameter("trip_id_fromschool"))); } else { transport.setBus_id(0); transport.setRoute_id(0); transport.setStop_id(0); transport.setTrip_id(0); } } return transport; } public Students getStudent(HttpServletRequest request) { Students student = new Students(); student.setFirst_name(request.getParameter("first_name")); student.setLast_name(request.getParameter("last_name")); student.setGr_number(request.getParameter("student_id")); student.setRfid_number(request.getParameter("rfid_number")); student.setGender(request.getParameter("gender")); student.setStudent_grade(request.getParameter("student_grade")); return student; } public Staff getStaff(HttpServletRequest request) { Staff staff= new Staff(); staff.setEmail(request.getParameter("email")); staff.setFull_name(request.getParameter("name")); staff.setGender(request.getParameter("gender")); staff.setMobile_number(request.getParameter("mobile")); staff.setRfid_number(request.getParameter("rfid_number")); staff.setStaff_id(request.getParameter("staff_id")); return staff; } public Parents getParent(HttpServletRequest request, int student_id) { // System.out.println(request.getParameter("parent_mobile")); Parents parent = new Parents(); parent.setFirst_name(request.getParameter("parent_firstname")); parent.setLast_name(request.getParameter("parent_lastname")); parent.setMobile(request.getParameter("parent_mobile").trim()); parent.setEmail(request.getParameter("parent_email")); parent.setStudent_id(student_id); return parent; } public Guardians getGuardian(HttpServletRequest request, int student_id) { // System.out.println(request.getParameter("parent_mobile")); Guardians parent = new Guardians(); parent.setFirst_name(request.getParameter("first_name")); parent.setLast_name(request.getParameter("last_name")); parent.setMobile_number(request.getParameter("mobile").trim()); parent.setEmail(request.getParameter("email")); parent.setRelation(request.getParameter("relation")); parent.setStudent_id(student_id); return parent; } public Address getAddress(HttpServletRequest request, int id, String subscriber_type) { Address address = new Address(); address.setCity(request.getParameter("city")); address.setCountry(request.getParameter("country")); address.setPostal(request.getParameter("postal")); address.setState(request.getParameter("state")); address.setStreet(request.getParameter("street")); address.setSubscriber_id(id); address.setSubscriber_type(subscriber_type); return address; } public Alerts getAlerts(HttpServletRequest request, int id, String subscriber_type, String alerts_type) { Alerts alerts = new Alerts(); alerts.setAlert_type(alerts_type); alerts.setSubscriber_id(id); alerts.setSubscriber_type(subscriber_type); if (alerts_type.equals("email")) { alerts.setAll_alerts(request.getParameter("email_all")); alerts.setIrregularities(request.getParameter("email_irregularities")); alerts.setLate(request.getParameter("email_late")); alerts.setNo_show(request.getParameter("email_noshow")); alerts.setRegularities(request.getParameter("email_regularities")); if (request.getParameter("email_all") == null) alerts.setAll_alerts("off"); else alerts.setAll_alerts(request.getParameter("email_all")); if (request.getParameter("email_irregularities") == null) alerts.setIrregularities("off"); else alerts.setIrregularities(request.getParameter("email_irregularities")); if(request.getParameter("email_late")==null) alerts.setLate("off"); else alerts.setLate(request.getParameter("email_late")); if(request.getParameter("email_noshow")==null) alerts.setNo_show("off"); else alerts.setNo_show(request.getParameter("email_noshow")); if(request.getParameter("email_regularities") == null) alerts.setRegularities("off"); else alerts.setRegularities(request.getParameter("email_regularities")); } if (alerts_type.equals("sms")) { if (request.getParameter("sms_all") == null) alerts.setAll_alerts("off"); else alerts.setAll_alerts(request.getParameter("sms_all")); if (request.getParameter("sms_irregularities") == null) alerts.setIrregularities("off"); else alerts.setIrregularities(request.getParameter("sms_irregularities")); if(request.getParameter("sms_late")==null) alerts.setLate("off"); else alerts.setLate(request.getParameter("sms_late")); if(request.getParameter("sms_noshow")==null) alerts.setNo_show("off"); else alerts.setNo_show(request.getParameter("sms_noshow")); if(request.getParameter("sms_regularities") == null) alerts.setRegularities("off"); else alerts.setRegularities(request.getParameter("sms_regularities")); } return alerts; } /*public Address updateAddress(int id, HttpServletRequest request,String subscriber_type) { Address address=staffservice.getAddress(id); address.setCity(request.getParameter("city")); address.setCountry(request.getParameter("country")); address.setPostal(request.getParameter("postal")); address.setState(request.getParameter("state")); address.setStreet(request.getParameter("street")); address.setSubscriber_id(id); address.setSubscriber_type(subscriber_type); return address; }*/ } /* * Student[ first_name, last_name, student_id, rfid_number, gender] * * Parent[ parent_firstname, parent_lastname, parent_mobile, parent_email] * * * Transport[ bus_id_number_fromhome, route_id_fromhome, trip_id_fromhome, * stop_id_fromhome, bus_id_number_fromschool, route_id_fromschool, * trip_id_fromschool, stop_id_fromschool] * * Address [ street, city, state, postal, country ] * * Alerts [email_all, email_noshow, email_late, email_irregularities, * email_regularities, sms_all, sms_noshow, sms_late, sms_irregularities, * sms_regularities ] */ <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.android.gcm.server.Result; import com.main.sts.entities.Commuter; import com.main.sts.entities.PushMessage; @Service("pushNotificationService") public class PushNotificationService { @Autowired private CommuterService commuterService; @Autowired private GoogleGCMService googleGCMService; public boolean sendPushNotification(int commuter_id, String title, String message) { Commuter commuter = commuterService.getCommuterById(commuter_id); if (commuter != null) { String gcm_regId = commuter.getGcm_reg_id(); return sendPushNotification(gcm_regId, title, message); } else { System.out.println("Couldnt fetch commuter information"); } return false; } public boolean sendPushNotification(String gcm_regId, String title, String message) { PushMessage pushMsg = new PushMessage(); pushMsg.setGcm_regid(gcm_regId); pushMsg.setTitle(title); pushMsg.setMessage(message); Result result = googleGCMService.sendPushNotification(pushMsg); if (result != null) { System.out.println("Sent push Notification with message id:" + result.getMessageId()); return true; } else { return false; } } public boolean sendPushNotificationToAllUsers(String title, String message) { boolean status = true; List<Commuter> commuters = commuterService.findAll(); if (commuters != null && commuters.size() > 0) { for (Commuter commuter : commuters) { status = status && sendPushNotification(commuter.getGcm_reg_id(), title, message); } } return status; } } <file_sep>/** * */ package com.main.sts.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.apache.log4j.Logger; import com.main.sts.entities.DashboardSettings; public class MyThreadPoolExecutor { private static final Logger logger = Logger.getLogger(MyThreadPoolExecutor.class); String toAddress1, subject1, sendMesg1; Session session1; DashboardSettings adminPreferences1; ArrayList<String> mobile1 = new ArrayList<String>(); String msg; static String res = ""; int poolSize = 2; int maxPoolSize = 2; long keepAliveTime = 10; ThreadPoolExecutor threadPool = null; final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10); public MyThreadPoolExecutor() { threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, queue); } public void runTask(Runnable task) { // System.out.println("Task count.."+threadPool.getTaskCount() ); // System.out.println("Queue Size before assigning the // task.."+queue.size() ); threadPool.execute(task); // System.out.println("Queue Size after assigning the // task.."+queue.size() ); // System.out.println("Pool Size after assigning the // task.."+threadPool.getActiveCount() ); // System.out.println("Task count.."+threadPool.getTaskCount() ); System.out.println("Task count.." + queue.size()); } public void shutDown() { threadPool.shutdown(); } public String sendMailThread(String toAddress, String subject, String sendMesg, Session session, DashboardSettings adminPreferences) { // System.out.println(adminPreferences); this.session1 = session; this.toAddress1 = toAddress; this.subject1 = subject; this.sendMesg1 = sendMesg; this.adminPreferences1 = adminPreferences; try { MyThreadPoolExecutor emailThreadPoolExecutor = new MyThreadPoolExecutor(); emailThreadPoolExecutor.runTask(new Runnable() { public void run() { try { System.out.println("session " + toAddress1); Message message = new MimeMessage(session1); message.setFrom(new InternetAddress(adminPreferences1.getFrom_email(), "PlexusTeam")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress1)); message.setSubject(subject1); message.setContent(sendMesg1, "text/html"); Transport.send(message); // Thread.sleep(3000); // System.out.println("completed"); logger.info("sent mail to [ " + toAddress1 + " ] about [ " + subject1 + " ]"); // MyThreadPoolExecutor.res="success"; } catch (AddressException ae) { ae.printStackTrace(); // MyThreadPoolExecutor.res="failure"; } catch (MessagingException me) { // TODO Auto-generated catch block me.printStackTrace(); // MyThreadPoolExecutor.res="failure"; } catch (Exception e) { e.printStackTrace(); // MyThreadPoolExecutor.res="failure"; } } }); } catch (Exception e) { e.printStackTrace(); // MyThreadPoolExecutor.res="failure"; } // System.out.println("res in thread "+MyThreadPoolExecutor.res); return res; } public void sendMailThreadWithAttach(final String toAddress, final String subject, final String sendMesg, final Session session, final DashboardSettings adminPreferences, final File file, final File csvfile) { // System.out.println(adminPreferences); this.session1 = session; this.toAddress1 = toAddress; this.subject1 = subject; this.sendMesg1 = sendMesg; this.adminPreferences1 = adminPreferences; try { MyThreadPoolExecutor emailThreadPoolExecutor = new MyThreadPoolExecutor(); emailThreadPoolExecutor.runTask(new Runnable() { public void run() { try { Message message = new MimeMessage(session1); message.setFrom(new InternetAddress(adminPreferences1.getFrom_email())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddress1)); message.setSubject(subject1); /* * DataSource source = new * FileDataSource(file.getAbsolutePath()); * message.setDataHandler(new DataHandler(source)); * * logger.info("Absolute path of file is" + * file.getAbsolutePath()); Multipart multipart = new * MimeMultipart(); BodyPart messageBodyPart = new * MimeBodyPart(); //messageBodyPart.setText(sendMesg); * message * .setFileName(file.getAbsolutePath().toString()); * multipart.addBodyPart(messageBodyPart); * logger.info("Added attachment to email"); // Send the * complete message parts message.setContent(multipart); * Transport.send(message); // Thread.sleep(1000); * file.delete(); */ Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(adminPreferences.getFrom_email())); InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part // MimeBodyPart messageBodyPart = new MimeBodyPart(); // creates multi-part Multipart multipart = new MimeMultipart(); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<html><b>" + sendMesg + "</b></html>", "text/html"); // adds attachments MimeBodyPart attachPart = new MimeBodyPart(); attachPart.attachFile(file.getAbsoluteFile()); multipart.addBodyPart(attachPart); multipart.addBodyPart(htmlPart); // csv attachment by sami only below code added MimeBodyPart csvattach = new MimeBodyPart(); csvattach.attachFile(csvfile.getAbsoluteFile()); multipart.addBodyPart(csvattach); // ended // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); csvfile.delete(); } catch (AddressException ae) { // TODO Auto-generated catch block ae.printStackTrace(); } catch (MessagingException me) { // TODO Auto-generated catch block me.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } logger.info("sent mail to [ " + toAddress + " ] with report as an attachment [ " + subject + " ]"); } @SuppressWarnings("deprecation") public void sendSmsToIndiaThread(ArrayList<String> mobile, String message) { // System.out.println(adminPreferences); this.mobile1 = mobile; this.msg = message; try { MyThreadPoolExecutor smsThreadPoolExecutor = new MyThreadPoolExecutor(); smsThreadPoolExecutor.runTask(new Runnable() { public void run() { try { String authkey = "<KEY>"; logger.info("Sending messages to : " + mobile1.toString()); String senderId = "slabss"; ArrayList<String> al = mobile1; String numbers = ""; for (String s : al) { numbers += s + ","; } // Your message to send, Add URL endcoding here. /* String message = "from string Some Test message"; */ // define route String route = "default"; // Prepare Url URLConnection myURLConnection = null; URL myURL = null; @SuppressWarnings("unused") BufferedReader buffreader = null; // encoding message String encoded_message = URLEncoder.encode(msg); // Send SMS API String mainUrl = "http://login.bulksmsglobal.in/sendhttp.php?"; // Prepare parameter string StringBuilder sbPostData = new StringBuilder(mainUrl); sbPostData.append("authkey=" + authkey); sbPostData.append("&mobiles=" + numbers); sbPostData.append("&message=" + encoded_message); sbPostData.append("&route=" + route); sbPostData.append("&sender=" + senderId); // final string mainUrl = sbPostData.toString(); // prepare connection myURL = new URL(mainUrl); myURLConnection = myURL.openConnection(); myURLConnection.connect(); buffreader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream())); logger.info("Sms sent..."); // finally close connection } catch (IOException ie) { ie.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } logger.info("sent sms about [ " + msg + " ]"); } } <file_sep>package com.main.sts.dto; import java.io.Serializable; import java.util.Date; import com.main.sts.entities.Buses; import com.main.sts.entities.RouteStops; import com.main.sts.entities.TripDetail; import com.main.sts.entities.Trips; public class ShuttleTimingsDTO implements Serializable { public static final long serialVersionUID = 1L; // id and trip_id both are same. they are only for backward comaptability. private int id; public int trip_id; public String trip_name; public String trip_display_name; public String trip_type; public int seats_filled; public int busid; public int routeid; public Date trip_running_date; private String vehicle_model; // If trip is enabled or not. like trip for a holiday wouldnt be active. private Boolean enabled; // if trip is active or not, like trip got completed before it can be // booked. private boolean active = false; /** * Number of seats available. */ private int seats_available; // 9.30 public String pickup_stop_time; // AM or PM public String pickup_stop_time_ampm; private String eta; // AM or PM private String eta_ampm; // will be shown to user, how much we are goign to charge private Integer charged_fare; public int getId() { return id;// getTrip_id(); } public void setId(int id) { this.id = id; setTrip_id(id); } public int getTrip_id() { return trip_id; } public void setTrip_id(int trip_id) { this.trip_id = trip_id; this.id = trip_id; } public String getTrip_name() { return trip_name; } public void setTrip_name(String trip_name) { this.trip_name = trip_name; } public String getTrip_display_name() { return trip_display_name; } public void setTrip_display_name(String trip_display_name) { this.trip_display_name = trip_display_name; } public String getTrip_type() { return trip_type; } public void setTrip_type(String trip_type) { this.trip_type = trip_type; } public int getSeats_filled() { return seats_filled; } public void setSeats_filled(int seats_filled) { this.seats_filled = seats_filled; } public int getBusid() { return busid; } public void setBusid(int busid) { this.busid = busid; } public int getRouteid() { return routeid; } public void setRouteid(int routeid) { this.routeid = routeid; } public Date getTrip_running_date() { return trip_running_date; } public void setTrip_running_date(Date trip_running_date) { this.trip_running_date = trip_running_date; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public int getSeats_available() { return seats_available; } public void setSeats_available(int seats_available) { this.seats_available = seats_available; } // public static ShuttleTimingsDTO toTripResponse(Trips t) { // return toTripResponse(t, false); // } public String getVehicle_model() { return vehicle_model; } public void setVehicle_model(String vehicle_model) { this.vehicle_model = vehicle_model; } public String getPickup_stop_time() { return pickup_stop_time; } public void setPickup_stop_time(String pickup_stop_time) { this.pickup_stop_time = pickup_stop_time; } public String getPickup_stop_time_ampm() { return pickup_stop_time_ampm; } public void setPickup_stop_time_ampm(String pickup_stop_time_ampm) { this.pickup_stop_time_ampm = pickup_stop_time_ampm; } public String getEta() { return eta; } public void setEta(String eta) { this.eta = eta; } public String getEta_ampm() { return eta_ampm; } public void setEta_ampm(String eta_ampm) { this.eta_ampm = eta_ampm; } public Integer getCharged_fare() { return charged_fare; } public void setCharged_fare(Integer charged_fare) { this.charged_fare = charged_fare; } public static ShuttleTimingsDTO toTripResponse(Trips t, RouteStops rs, boolean seatsAvailableCheck) { ShuttleTimingsDTO tr = new ShuttleTimingsDTO(); tr.id = t.getId(); tr.trip_id = t.getId(); tr.seats_filled = t.getSeats_filled(); tr.trip_running_date = t.getTrip_running_date(); tr.enabled = t.getEnabled(); tr.active = t.isActive(); if (seatsAvailableCheck) { Buses bus = t.getTripDetail().getBus(); int allocated_seats = bus.getBus_allotted(); if (allocated_seats >= tr.seats_filled) { tr.seats_available = allocated_seats - tr.seats_filled; } else { tr.seats_available = 0; } } TripDetail td = t.getTripDetail(); tr.busid = td.getBusid(); tr.routeid = td.getRouteid(); tr.trip_name = td.getTrip_name(); tr.trip_display_name = td.getTrip_display_name(); // for some use-case it needs like where we show the trip timings, for // showing the vehicle type. tr.vehicle_model = t.getTripDetail().getBus().getBus_make_model(); tr.pickup_stop_time = rs.getStop_time(); Integer hours = Integer.parseInt(rs.getStop_time().split(":")[0]); tr.pickup_stop_time_ampm = hours < 12 ? "AM" : "PM"; // TODO: implements ETA tr.eta = null; tr.eta_ampm = null; return tr; } @Override public String toString() { return "ShuttleTimingsDTO [id=" + id + ", trip_id=" + trip_id + ", trip_name=" + trip_name + ", trip_display_name=" + trip_display_name + ", trip_type=" + trip_type + ", seats_filled=" + seats_filled + ", busid=" + busid + ", routeid=" + routeid + ", trip_running_date=" + trip_running_date + ", vehicle_model=" + vehicle_model + ", enabled=" + enabled + ", active=" + active + ", seats_available=" + seats_available + ", pickup_stop_time=" + pickup_stop_time + ", pickup_stop_time_ampm=" + pickup_stop_time_ampm + ", eta=" + eta + ", eta_ampm=" + eta_ampm + "]"; } } <file_sep>package com.main.sts.dto; import java.io.Serializable; public class RechargeOptionsRequest implements Serializable { private Integer commuter_id; public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } @Override public String toString() { return "RechargeOptionsRequest [commuter_id=" + commuter_id + "]"; } } <file_sep>package com.main.sts.dto.response; import java.io.Serializable; public class CommuterResponse implements Serializable { public int commuter_id; public int pickup_stop_id; public int dropoff_stop_id; public String pickup_stop_name; public String dropoff_stop_name; public int charged_fare; public String commuter_name; public String mobile; public int booking_id; public int booking_status; public Boolean is_pickup = null; public String type = null; public int num_seats_booked; public int getCommuter_id() { return commuter_id; } public void setCommuter_id(int commuter_id) { this.commuter_id = commuter_id; } public int getPickup_stop_id() { return pickup_stop_id; } public void setPickup_stop_id(int pickup_stop_id) { this.pickup_stop_id = pickup_stop_id; } public int getDropoff_stop_id() { return dropoff_stop_id; } public void setDropoff_stop_id(int dropoff_stop_id) { this.dropoff_stop_id = dropoff_stop_id; } public String getPickup_stop_name() { return pickup_stop_name; } public void setPickup_stop_name(String pickup_stop_name) { this.pickup_stop_name = pickup_stop_name; } public String getDropoff_stop_name() { return dropoff_stop_name; } public void setDropoff_stop_name(String dropoff_stop_name) { this.dropoff_stop_name = dropoff_stop_name; } public int getCharged_fare() { return charged_fare; } public void setCharged_fare(int charged_fare) { this.charged_fare = charged_fare; } public String getCommuter_name() { return commuter_name; } public void setCommuter_name(String commuter_name) { this.commuter_name = commuter_name; } public int getBooking_id() { return booking_id; } public void setBooking_id(int booking_id) { this.booking_id = booking_id; } public Boolean getIs_pickup() { return is_pickup; } public void setIs_pickup(Boolean is_pickup) { this.is_pickup = is_pickup; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getBooking_status() { return booking_status; } public void setBooking_status(int booking_status) { this.booking_status = booking_status; } public int getNum_seats_booked() { return num_seats_booked; } public void setNum_seats_booked(int num_seats_booked) { this.num_seats_booked = num_seats_booked; } @Override public String toString() { return "CommuterResponse [commuter_id=" + commuter_id + ", pickup_stop_id=" + pickup_stop_id + ", dropoff_stop_id=" + dropoff_stop_id + ", pickup_stop_name=" + pickup_stop_name + ", dropoff_stop_name=" + dropoff_stop_name + ", charged_fare=" + charged_fare + ", commuter_name=" + commuter_name + ", booking_id=" + booking_id + ", is_pickup=" + is_pickup + ", type=" + type + "]"; } } <file_sep>package com.main.sts.service; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import org.springframework.stereotype.Service; import com.google.gson.Gson; import com.main.sts.dto.GoogleDistancePojo; import com.main.sts.service.VehicleTrackingService.DistanceMatrix; @Service("googleMapService") public class GoogleMapService { // String myURL = // "https://maps.googleapis.com/maps/api/distancematrix/json?" // + "origins=17.446251,78.349546&destinations=17.451533,78.380947"; public static final String GOOGLEMAP_DISTANCE_URL = "https://maps.googleapis.com/maps/api/distancematrix/json?" + "origins=%s,%s&destinations=%s,%s"; public DistanceAndTimeDuration getDistanceAndTimeDuration(DistanceMatrix dm) { GoogleDistancePojo distance = findDistance(dm); System.out.println(distance); // distance System.out.println(distance.getRows()[0].getElements()[0].getDistance().getText()); // duration System.out.println(distance.getRows()[0].getElements()[0].getDuration().getText()); DistanceAndTimeDuration dtd = new DistanceAndTimeDuration(); dtd.distance = distance.getRows()[0].getElements()[0].getDistance().getText(); dtd.time_duration = distance.getRows()[0].getElements()[0].getDuration().getText(); System.out.println(dtd); return dtd; } public GoogleDistancePojo findDistance(DistanceMatrix dm) { String urlStr = String.format(GOOGLEMAP_DISTANCE_URL, dm.vehicle_lat, dm.vehicle_long, dm.booking_stop_lat, dm.booking_stop_long); System.out.println("Requeted URL:" + urlStr); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(urlStr); urlConn = url.openConnection(); if (urlConn != null) //urlConn.setReadTimeout(60 * 1000); if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { throw new RuntimeException("Exception while calling URL:" + urlStr, e); } String json = sb.toString(); if (json != null) { return new Gson().fromJson(json, GoogleDistancePojo.class); } else { return null; } } public static void main(String[] args) { GoogleMapService mapService = new GoogleMapService(); DistanceMatrix dm = new DistanceMatrix(); dm.vehicle_lat = "17.446251"; dm.vehicle_long = "78.349546"; dm.booking_stop_lat = "17.451533"; dm.booking_stop_long = "78.380947"; GoogleDistancePojo distance = mapService.findDistance(dm); System.out.println(distance); // distance System.out.println(distance.getRows()[0].getElements()[0].getDistance().getText()); // duration System.out.println(distance.getRows()[0].getElements()[0].getDuration().getText()); DistanceAndTimeDuration dtd = new DistanceAndTimeDuration(); dtd.distance = distance.getRows()[0].getElements()[0].getDistance().getText(); dtd.time_duration = distance.getRows()[0].getElements()[0].getDuration().getText(); System.out.println(dtd); } public static class DistanceAndTimeDuration { public String distance; public String time_duration; @Override public String toString() { return "DistanceAndTimeDuration [distance=" + distance + ", timeduration=" + time_duration + "]"; } } } <file_sep>package com.main.sts.messageworkers; public class Sms { private String sendTo; private String message; public Sms(String sendTo, String message) { this.message = message; this.sendTo = sendTo; } public String getSendTo() { return sendTo; } public String getMessage() { return message; } @Override public String toString() { return "Sms [sendTo=" + sendTo + ", message=" + message + "]"; } } <file_sep>package com.main.sts.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.RfidDao; import com.main.sts.entities.RfidCards; @Service public class RfidCardsService { @Autowired private RfidDao rfidDao; public List<RfidCards> getRfidsByType(String type) { List<RfidCards> cards = rfidDao.listRfids(type); return cards; } public RfidCards getRfidCard(String rfid_number) { return rfidDao.getRfid(rfid_number); } public RfidCards getRfidCard(int id) { return rfidDao.getRfid(id); } public List<RfidCards> getAvailableRfids(String type, int rfid_status) { List<RfidCards> cards = rfidDao.listAvailableRfids(type, rfid_status); return cards; } public void addRfid(String rfid_number, String type) { RfidCards cards = new RfidCards(); cards.setAllocated_time("none"); cards.setAvailable(0); cards.setRfid_number(rfid_number); cards.setType(type); cards.setAllocated_person_name("none"); cards.setActive(0); rfidDao.insertRfid(cards); } public boolean rfidExists(String rfid_number) { RfidCards card = rfidDao.getRfid(rfid_number); if (card == null) return false; else return true; } public boolean updateRfid(String current_rfid, String new_rfid) { boolean ret = false; try { if (rfidExists(new_rfid)) { ret = false; } else { rfidDao.updateRfidNumber(current_rfid, new_rfid); ret = true; } } catch (Exception e) { e.printStackTrace(); } return ret; } public boolean deleteRfid(String rfid_number) { try { RfidCards cards = rfidDao.getRfid(rfid_number); rfidDao.deleteRfid(cards.getId()); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public List<RfidCards> searchRfids(String str, String type) { List<RfidCards> cards = rfidDao.searchRfids(str, type); return cards; } public void updateRfidWhenAllocated(int allocated_to, String allocated_person_name, String rfid_number) { RfidCards cards = getRfidCard(rfid_number); cards.setAllocated_person_name(allocated_person_name); cards.setAllocated_time(new Date().toString()); cards.setAvailable(1); cards.setAllocated_to(allocated_to); rfidDao.updateRfid(cards); } public void updateRfidWhenDeallocated(String rfid_number) { RfidCards cards = getRfidCard(rfid_number); cards.setAllocated_person_name("none"); cards.setAllocated_time("none"); cards.setAvailable(0); cards.setAllocated_to(0); rfidDao.updateRfid(cards); } public void deleteRfid(RfidCards rfidCard) { rfidDao.deleteEntity(rfidCard); } } <file_sep>package com.main.sts.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.StaffDao; import com.main.sts.entities.Address; import com.main.sts.entities.Alerts; import com.main.sts.entities.Buses; import com.main.sts.entities.Staff; import com.main.sts.entities.Transport; import com.main.sts.entities.Trips; import com.main.sts.util.MakeObjects; import com.main.sts.util.StaffJspEntity; import com.main.sts.util.SystemConstants; @Service public class StaffService { private static final Logger logger = Logger.getLogger(Staff.class); @Autowired private StaffDao staffdao; @Autowired private MakeObjects makeObjects; @Autowired private RfidCardsService rfidCardsService; @Autowired private TripService tripService; @Autowired private BusesService busesService; @Autowired private TransportService transportService; private final static String subscriber_type = "staff"; private final static String alerts_type_sms = "sms"; private final static String alerts_type_email = "email"; public void addStaff(HttpServletRequest request) { Staff staff = makeObjects.getStaff(request); staffdao.insert(staff); rfidCardsService.updateRfidWhenAllocated(staff.getId(), staff.getFull_name(), staff.getRfid_number()); Address address = makeObjects.getAddress(request, staff.getId(), subscriber_type); staffdao.insertAddress(address); Alerts smsalert = makeObjects.getAlerts(request, staff.getId(), subscriber_type, alerts_type_sms); staffdao.insertAlert(smsalert); Alerts emailalert = makeObjects.getAlerts(request, staff.getId(), subscriber_type, alerts_type_email); staffdao.insertAlert(emailalert); Transport from_home = makeObjects.getTransport(request, staff.getId(), subscriber_type, SystemConstants.PICKUP); staffdao.insertTransport(from_home); Transport from_school = makeObjects.getTransport(request, staff.getId(), subscriber_type, SystemConstants.DROPOFF); staffdao.insertTransport(from_school); if (request.getParameter("trip_id_fromhome").length() != 0) if (busSeatsAvailable(Integer.parseInt(request.getParameter("trip_id_fromhome")))) tripService.incrementTripSeat(from_home.getTrip_id()); if (request.getParameter("trip_id_fromschool").length() != 0) if (busSeatsAvailable(Integer.parseInt(request.getParameter("trip_id_fromschool")))){ System.out.println("from school "+from_school.getTrip_id()); tripService.incrementTripSeat(from_school.getTrip_id()); } logger.info("Staff [ " + staff.getFull_name() + " ] has been Added"); } public void updateStaff(HttpServletRequest request) { String new_rfid = request.getParameter("rfid_number"); Staff st = staffdao.getStaff(Integer.parseInt(request.getParameter("id"))); //System.out.println("staff "+st); String rfid_num = null; if (new_rfid.length() > 6) { // System.out.println("new==>" + new_rfid); rfidCardsService.updateRfidWhenDeallocated(st.getRfid_number()); rfidCardsService.updateRfidWhenAllocated(st.getId(), st.getFull_name(), new_rfid); rfid_num = new_rfid; } else { rfid_num = st.getRfid_number(); } Staff staff = makeObjects.getStaff(request); // System.out.println(staff); staff.setId(st.getId()); staff.setRfid_number(rfid_num); // System.out.println(staff); staffdao.update(staff); Transport transport = transportService.getTransport(st.getId(), "staff", SystemConstants.PICKUP); Transport homeTransport = makeObjects.getTransport(request, st.getId(), "staff", SystemConstants.PICKUP); homeTransport.setId(transport.getId()); // System.out.println(homeTransport); if (request.getParameter("bus_id_number_fromhome").length() != 0) { staffdao.updateEntity(homeTransport); } Transport transport1 = transportService.getTransport(st.getId(), "staff", SystemConstants.DROPOFF); Transport schoolTransport = makeObjects.getTransport(request, st.getId(), "staff", SystemConstants.DROPOFF); schoolTransport.setId(transport1.getId()); if (request.getParameter("bus_id_number_fromschool").length() != 0) { staffdao.updateEntity(schoolTransport); } Address add = getAddress(st.getId(), "staff"); // System.out.println(add); Address address = makeObjects.getAddress(request, st.getId(), "staff"); address.setId(add.getId()); staffdao.updateEntity(address); Alerts email_al = getAlerts(st.getId(), "staff", "email"); Alerts sms_al = getAlerts(st.getId(), "staff", "sms"); Alerts emailAlerts = makeObjects.getAlerts(request, st.getId(), "staff", "email"); Alerts smsAlerts = makeObjects.getAlerts(request, st.getId(), "staff", "sms"); emailAlerts.setId(email_al.getId()); smsAlerts.setId(sms_al.getId()); staffdao.updateEntity(emailAlerts); staffdao.updateEntity(smsAlerts); if (request.getParameter("trip_id_fromhome").length() != 0) { int trip_id_from_home = Integer.parseInt(request.getParameter("trip_id_fromhome")); if (busSeatsAvailable(trip_id_from_home)) { tripService.incrementTripSeat(homeTransport.getTrip_id()); if (transport.getTrip_id() != 0) if(transport.getTrip_id()!=homeTransport.getTrip_id()) tripService.decrementTripSeat(transport.getTrip_id()); } } if (request.getParameter("trip_id_fromschool").length() != 0) { int trip_id_from_school = Integer.parseInt(request.getParameter("trip_id_fromschool")); if (busSeatsAvailable(trip_id_from_school)) { tripService.incrementTripSeat(schoolTransport.getTrip_id()); if (transport1.getTrip_id() != 0) if(transport1.getTrip_id()!=schoolTransport.getTrip_id()) { System.out.println("trip from school"); tripService.decrementTripSeat(transport1.getTrip_id()); } } } /*if (transport.getTrip_id() != 0) if(transport.getTrip_id()!=homeTransport.getTrip_id()){ System.out.println("trip from school 1"); tripService.decrementTripSeat(transport.getTrip_id()); } if (transport1.getTrip_id() != 0) if(transport1.getTrip_id()!=schoolTransport.getTrip_id()){ System.out.println("trip from school 2"); tripService.decrementTripSeat(transport1.getTrip_id()); }*/ logger.info("Staff [ " + staff.getFull_name() + " ] has been updated"); } public void deleteStaff(int staff_id) { Staff staff = staffdao.getStaff(staff_id); rfidCardsService.updateRfidWhenDeallocated(staff.getRfid_number()); staffdao.deleteEntity(staff); Address address = getAddress(staff_id, subscriber_type); staffdao.deleteEntity(address); Transport homeTransport = transportService.getTransport(staff.getId(), "staff", SystemConstants.PICKUP); if (homeTransport.getTrip_id() != 0) { tripService.decrementTripSeat(homeTransport.getTrip_id()); staffdao.deleteEntity(homeTransport); } Transport schoolTransport = transportService.getTransport(staff.getId(), "staff", SystemConstants.DROPOFF); if (schoolTransport.getTrip_id() != 0) { System.out.println("delete staff"); tripService.decrementTripSeat(schoolTransport.getTrip_id()); // System.out.println(schoolTransport.getTrip_id()); staffdao.deleteEntity(schoolTransport); } Alerts email_al = getAlerts(staff.getId(), "staff", "email"); Alerts sms_al = getAlerts(staff.getId(), "staff", "sms"); staffdao.deleteEntity(sms_al); staffdao.deleteEntity(email_al); logger.info("staff [ " + staff.getFull_name() + " ] has been deleted"); } public Staff getStaffByStaffId(String staff_id) { return staffdao.getstaff(staff_id); } public List<Staff> getStaff() { return staffdao.getStaff(); } public Staff getStaffById(int id) { return staffdao.getStaff(id); } public Address getAddress(int subscriber_id, String type) { return staffdao.getAddress(subscriber_id, type); } public Transport getTransport(int subscriber_id, String trans_type) { return staffdao.getTransport(subscriber_id, trans_type); } public Alerts getAlerts(int subscriber_id, String type, String alert_type) { return staffdao.getAlerts(subscriber_id, type, alert_type); } public boolean busSeatsAvailable(int trip_id) { Trips trip = tripService.getTrip(trip_id); int seats_filled = trip.getSeats_filled(); Buses buses = busesService.getBusById(trip.getTripDetail().getBusid()); int total_seats = Integer.parseInt(buses.getBus_capacity()); if (seats_filled == total_seats) { return false; } else { return true; } } public List<StaffJspEntity> getStaffDetails() { return staffdao.getStaffDetails(); } public List<StaffJspEntity> searchStaff(String column, String value) { return staffdao.search(column, value); } } <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.entities.Commuter; @Service("smsService") public class SMSService { @Autowired private CommuterService commuterService; @Autowired private Msg91SMSService smsServiceProvider; public boolean sendSMS(final String[] ids, final String message) { // String[] commuterIds = ids; // if (ids != null && ids.length == 1) { // String id = ids[0]; // if (Integer.parseInt(id) == Integer.MIN_VALUE) { // ids = commuterService.getActiveAndVerifiedCommuterIds(); // commuterIds = ids; // } // } Thread t = new Thread(new Runnable() { @Override public void run() { for (String id : ids) { Commuter c = commuterService.getCommuterById(Integer.parseInt(id)); long number = Long.parseLong(c.getMobile()); if (number == 9866694931L || number == 8123829624L || number == 9441501647L || number == 9347347329L || number == 9000990610L) { // ignore this stupid fellow. continue; } if (c.getStatus() == 0) { continue; } System.out.println(number); boolean sent = sendSMS(number, message); System.out.println("sent to:" + number + " with status:" + sent); try { Thread.sleep(6000L); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Sent to all users: exiting"); } }); t.start(); System.out.println("Request for sending SMS submitted to number of people:" + ids.length); return true; } public boolean sendSMS(long number, String message) { SMSInfo smsInfo = new SMSInfo(); smsInfo.message = message; smsInfo.mobile = "" + number; smsInfo.sendEnabled = true; return smsServiceProvider.sendSMS(smsInfo); } } <file_sep>package com.main.sts.model; public class OldBusDetails { private String old_bus_licence_number_fromhome; private String old_bus_id_number_fromhome; private String old_route_name_fromhome; private String old_route_id_fromhome; private String old_trip_name_fromhome; private String old_trip_id_fromhome; private String old_stop_name_fromhome; private String old_stop_id_fromhome; private String old_bus_licence_number_fromschool; private String old_bus_id_number_fromschool; private String old_route_name_fromschool; private String old_route_id_fromschool; private String old_trip_name_fromschool; private String old_trip_id_fromschool; private String old_stop_name_fromschool; private String old_stop_id_fromschool; private String old_rfid_number; public String getOld_rfid_number() { return old_rfid_number; } public void setOld_rfid_number(String old_rfid_number) { this.old_rfid_number = old_rfid_number; } public String getOld_bus_licence_number_fromhome() { return old_bus_licence_number_fromhome; } public void setOld_bus_licence_number_fromhome( String old_bus_licence_number_fromhome) { this.old_bus_licence_number_fromhome = old_bus_licence_number_fromhome; } public String getOld_bus_id_number_fromhome() { return old_bus_id_number_fromhome; } public void setOld_bus_id_number_fromhome(String old_bus_id_number_fromhome) { this.old_bus_id_number_fromhome = old_bus_id_number_fromhome; } public String getOld_route_name_fromhome() { return old_route_name_fromhome; } public void setOld_route_name_fromhome(String old_route_name_fromhome) { this.old_route_name_fromhome = old_route_name_fromhome; } public String getOld_route_id_fromhome() { return old_route_id_fromhome; } public void setOld_route_id_fromhome(String old_route_id_fromhome) { this.old_route_id_fromhome = old_route_id_fromhome; } public String getOld_trip_name_fromhome() { return old_trip_name_fromhome; } public void setOld_trip_name_fromhome(String old_trip_name_fromhome) { this.old_trip_name_fromhome = old_trip_name_fromhome; } public String getOld_trip_id_fromhome() { return old_trip_id_fromhome; } public void setOld_trip_id_fromhome(String old_trip_id_fromhome) { this.old_trip_id_fromhome = old_trip_id_fromhome; } public String getOld_stop_name_fromhome() { return old_stop_name_fromhome; } public void setOld_stop_name_fromhome(String old_stop_name_fromhome) { this.old_stop_name_fromhome = old_stop_name_fromhome; } public String getOld_stop_id_fromhome() { return old_stop_id_fromhome; } public void setOld_stop_id_fromhome(String old_stop_id_fromhome) { this.old_stop_id_fromhome = old_stop_id_fromhome; } public String getOld_bus_licence_number_fromschool() { return old_bus_licence_number_fromschool; } public void setOld_bus_licence_number_fromschool( String old_bus_licence_number_fromschool) { this.old_bus_licence_number_fromschool = old_bus_licence_number_fromschool; } public String getOld_bus_id_number_fromschool() { return old_bus_id_number_fromschool; } public void setOld_bus_id_number_fromschool(String old_bus_id_number_fromschool) { this.old_bus_id_number_fromschool = old_bus_id_number_fromschool; } public String getOld_route_name_fromschool() { return old_route_name_fromschool; } public void setOld_route_name_fromschool(String old_route_name_fromschool) { this.old_route_name_fromschool = old_route_name_fromschool; } public String getOld_route_id_fromschool() { return old_route_id_fromschool; } public void setOld_route_id_fromschool(String old_route_id_fromschool) { this.old_route_id_fromschool = old_route_id_fromschool; } public String getOld_trip_name_fromschool() { return old_trip_name_fromschool; } public void setOld_trip_name_fromschool(String old_trip_name_fromschool) { this.old_trip_name_fromschool = old_trip_name_fromschool; } public String getOld_trip_id_fromschool() { return old_trip_id_fromschool; } public void setOld_trip_id_fromschool(String old_trip_id_fromschool) { this.old_trip_id_fromschool = old_trip_id_fromschool; } public String getOld_stop_name_fromschool() { return old_stop_name_fromschool; } public void setOld_stop_name_fromschool(String old_stop_name_fromschool) { this.old_stop_name_fromschool = old_stop_name_fromschool; } public String getOld_stop_id_fromschool() { return old_stop_id_fromschool; } public void setOld_stop_id_fromschool(String old_stop_id_fromschool) { this.old_stop_id_fromschool = old_stop_id_fromschool; } @Override public String toString() { return "OldBusDetails [old_bus_licence_number_fromhome=" + old_bus_licence_number_fromhome + ", old_bus_id_number_fromhome=" + old_bus_id_number_fromhome + ", old_route_name_fromhome=" + old_route_name_fromhome + ", old_route_id_fromhome=" + old_route_id_fromhome + ", old_trip_name_fromhome=" + old_trip_name_fromhome + ", old_trip_id_fromhome=" + old_trip_id_fromhome + ", old_stop_name_fromhome=" + old_stop_name_fromhome + ", old_stop_id_fromhome=" + old_stop_id_fromhome + ", old_bus_licence_number_fromschool=" + old_bus_licence_number_fromschool + ", old_bus_id_number_fromschool=" + old_bus_id_number_fromschool + ", old_route_name_fromschool=" + old_route_name_fromschool + ", old_route_id_fromschool=" + old_route_id_fromschool + ", old_trip_name_fromschool=" + old_trip_name_fromschool + ", old_trip_id_fromschool=" + old_trip_id_fromschool + ", old_stop_name_fromschool=" + old_stop_name_fromschool + ", old_stop_id_fromschool=" + old_stop_id_fromschool + ", old_rfid_number=" + old_rfid_number + "]"; } } <file_sep>package com.main.sts.service; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.TimeUnit; import org.apache.commons.codec.binary.Base64; import org.hibernate.criterion.Order; import org.hibernate.service.spi.ServiceException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.common.CommonConstants; import com.main.sts.common.CommonConstants.TransactionStatus; import com.main.sts.common.CommonConstants.UserActiveType; import com.main.sts.common.CommonConstants.UserChannelType; import com.main.sts.common.CommonConstants.UserStatusType; import com.main.sts.dao.sql.CommuterDao; import com.main.sts.dto.CommuterDTO; import com.main.sts.dto.EmailDTO; import com.main.sts.dto.EmailResponse; import com.main.sts.entities.Account; import com.main.sts.entities.Commuter; import com.main.sts.entities.CorporateReferralCode; import com.main.sts.entities.DashboardSettings; import com.main.sts.entities.PushMessage; import com.main.sts.entities.ReferralCode; import com.main.sts.entities.ReferralTransactionInfo; import com.main.sts.entities.SMSCode; import com.main.sts.entities.TransactionInfo; import com.main.sts.util.MD5PassEncryptionClass; import com.main.sts.util.PasswordEncrypter; @Service("commuterService") public class CommuterService { private Random rand = new Random(100000); @Autowired private GoogleGCMService gcmService; @Autowired private CommuterDao commuterDao; // OTP @Autowired private SmsCodeService smsCodeService; @Autowired private Msg91SMSService smsService; @Autowired private TransactionService transactionService; @Autowired private SendGridMailProvider emailProvider; @Autowired private ReferralCodeService referralCodeService; @Autowired private TransactionService txService; @Autowired private ReferralTransactionService referralTxService; //@Autowired //private PushNotificationService pushNotificationService; @Autowired private NotificationService notificationService; @Autowired private AccountService accountService; @Autowired private DashBoardSettingsService settingsService; public CommuterService() { } public static final String DEFAULT_ENCODING = "UTF-8"; public static String base64encode(String text) { try { return new String(Base64.encodeBase64(text.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { return null; } }// base64encode public static String base64decode(String text) { try { return new String(Base64.decodeBase64(text.getBytes("UTF-8"))); } catch (IOException e) { return null; } } public List<Commuter> findAll() { return commuterDao.findAll(); } // TODO: fix it to take only active andd verified public List<Commuter> findAllActiveAndVerified() { return commuterDao.findAllActiveAndVerified(); } public List<Commuter> findAllActiveAndVerified(int offset, int limit) { return commuterDao.findAllActiveAndVerified(offset, limit); } public List<Commuter> findAll(int offset, int limit) { return commuterDao.findAll(); } public List<Commuter> getCommutersList(Integer offset, Integer limit) { return commuterDao.getCommutersList(offset, limit); } public Commuter getCommuterById(int commuter_id) { return commuterDao.getCommuter(commuter_id); } public boolean insertCommuter(Commuter commuter) { return commuterDao.insertCommuter(commuter); } public ReturnCodes registerCommuter(String name, String email, String mobile, String gender, String gcm_regId, String referral_code_used, String device_id, UserChannelType channelType, boolean smsSendEnabled) throws ServiceException { Commuter c1 = getCommuterByMobile(mobile); if (c1 != null && c1.getStatus() == 1) { System.out.println("User already exist, again generating an otp"); generateAndSendOTP(mobile, c1.getCommuter_id(), c1.getName(), smsSendEnabled); // Since User exist, generating an another OTP c1.setStatus(UserStatusType.REGISTED_NOT_ACTIVATED.getTypeCode()); boolean status = commuterDao.updateCommuter(c1); if (status) { System.out.println("Commuter id:" + c1.getCommuter_id() + " inactivated as new OTP generated"); } else { System.out.println("Failed to update in DB for commuter id:" + c1.getCommuter_id() + " inactivated as new OTP generated"); } return ReturnCodes.USER_ALREADY_EXIST; } else if (c1 != null && c1.getStatus() == 0) { System.out.println("User already exist but not activated due to Otp, resending an otp again"); generateAndSendOTP(mobile, c1.getCommuter_id(), c1.getName(), smsSendEnabled); return ReturnCodes.USER_EXIST_OTP_GENERATED; } else { Commuter commuter = new Commuter(); commuter.setName(name); commuter.setEmail(email); commuter.setMobile(mobile); commuter.setGender(gender); commuter.setGcm_reg_id(gcm_regId); // code by using a user is registering in system. commuter.setReferral_code_used(referral_code_used); commuter.setDevice_id(device_id); // Not verified commuter.setStatus(UserStatusType.REGISTED_NOT_ACTIVATED.getTypeCode()); commuter.setActive(UserActiveType.ACTIVE.getTypeCode());// active commuter.setChannel_type(channelType.intValue()); boolean success = insertCommuter(commuter); if (success) { System.out.println("Inserted commuter:" + email + " with id:" + commuter.getCommuter_id()); generateAndSendOTP(mobile, commuter.getCommuter_id(), commuter.getName(), smsSendEnabled); return ReturnCodes.USER_CREATED_OTP_GENERATED; } else { System.out.println("Failed to insert commuter:" + email); return ReturnCodes.USER_CREATION_FAILED; } } } public ReturnCodes unregisterCommuter(String mobile) { Commuter commuter = getCommuterByMobile(mobile); if (commuter == null) { return ReturnCodes.USER_NOT_EXIST; } boolean status = deleteCommuter(commuter); System.out.println("unregisterCommuter:status:" + status); if (status) { return ReturnCodes.USER_UNREGISTERED_SUCCESSFULLY; } else { return ReturnCodes.USER_UNREGISTRATION_FAILED; } } public boolean sendWelcomeSignupMessageSMS(Commuter commuter, int freeRidesGiven, boolean alreadyRegistrationExist, boolean smsSendEnabled) { String name = commuter.getName(); System.out.println("Sending welcome signup message on SMS to " + name); SMSInfo sms = new SMSInfo(); sms.mobile = commuter.getMobile(); if (alreadyRegistrationExist) { sms.message = String.format(CommonConstants.WELCOME_MSG_ALREADY_REGISTERED, name); } else { // ideally it shouldnt enter in else block as freeRides should be gt zero if (freeRidesGiven > 0) { sms.message = String.format(CommonConstants.WELCOME_MSG, name, freeRidesGiven); } else { sms.message = String.format(CommonConstants.WELCOME_MSG, name, CommonConstants.DEFAULT_SIGNUP_FREE_RIDES); } } System.out.println("msg:"+sms.message); sms.sendEnabled = smsSendEnabled; boolean status = smsService.sendSMS(sms); return status; } public void sendWelcomeSignupMessage(Commuter commuter, String gcm_regId) { PushMessage pushMessage = new PushMessage(); pushMessage.setGcm_regid(gcm_regId); String name = commuter.getName(); System.out.println("Sending welcome signup message"); pushMessage.setTitle(CommonConstants.NOTIFICATION_WELCOME_MSG_TITLE); if (name != null) { pushMessage.setMessage(String.format(CommonConstants.NOTIFICATION_WELCOME_MSG_NAME, name)); } else { pushMessage.setMessage(String.format(CommonConstants.NOTIFICATION_WELCOME_MSG)); } System.out.println("Sending welcome signup message:" + pushMessage.getMessage()); //this.sendPushMessage(pushMessage); int commuter_id = commuter.getCommuter_id(); System.out.println("notificationService:"+notificationService); this.notificationService.publishNotification(commuter_id, pushMessage); } // public void sendPushMessage(PushMessage pushMessage) { // try { // gcmService.sendPushNotification(pushMessage); // } catch (Exception e) { // // Suppress any exception comes in this. // e.printStackTrace(); // } // } public ReturnCodes updateGCMRegistrationId(int commuter_id, String gcm_regId) { Commuter commuter = getCommuterById(commuter_id); commuter.setGcm_reg_id(gcm_regId); boolean status = updateCommuter(commuter); if (status) { return ReturnCodes.GCM_REGISTRATION_SUCCESSFUL; } else { return ReturnCodes.GCM_REGISTRATION_FAILED; } } private void generateAndSendOTP(String mobile, int commuter_id, String name, boolean smsSendEnabled) { int otp = generateOtp(); boolean sent = sendOTP(mobile, otp, name, smsSendEnabled); System.out.println("OTP sent:" + sent + " for :" + commuter_id); boolean added = addToSMSCode(commuter_id, otp); if (added) { System.out.println("Added to SMS code successfully"); } else { System.out.println("Add to SMS code failed"); } } public int generateOtp() { int otp = rand.nextInt(1000000); System.out.println("otp:" + otp); return otp; } public boolean sendOTP(String mobile, int otp, String name, boolean smsSendEnabled) { SMSInfo sms = new SMSInfo(); sms.mobile = mobile; sms.message = String.format(CommonConstants.OTP_MSG, name, otp); sms.sendEnabled = smsSendEnabled; System.out.println("OTP message:"+sms.message); boolean status = smsService.sendSMS(sms); return status; } public Commuter getCommuterByMobile(String mobile) { return commuterDao.getCommuterByMobile(mobile); } public Commuter getCommuterByEmail(String email) { return commuterDao.getCommuterByEmail(email); } public boolean addToSMSCode(int commuter_id, int otp) { SMSCode smsCode = new SMSCode(); smsCode.setCommuter_id(commuter_id); smsCode.setCode(otp); smsCode.setStatus(0); boolean status = smsCodeService.insertSMSCode(smsCode); if (status) { return true; } return false; } // We shouldn't allow user to update his email id. public boolean updateCommuterDetails(CommuterDTO commuterDTO) { System.out.println("commuterDTO:"+commuterDTO); Commuter commuter = getCommuterById(commuterDTO.getCommuter_id()); if(commuter==null){ System.out.println("commuter shouldnt be null"); } System.out.println("commuter:"+commuter); // updating only these three details. Mobile no. should not be updated at all until unless deemed needed. commuter.setName(commuterDTO.getName()); commuter.setEmail(commuterDTO.getEmail()); commuter.setGender(commuterDTO.getGender()); commuter.setPassword(commuterDTO.getPassword()); return commuterDao.updateCommuter(commuter); } public boolean updateCommuterDetails(int commuter_id, String name, String email, String gender, String password, int status, int active) { Commuter commuter = getCommuterById(commuter_id); if(commuter==null){ System.out.println("commuter shouldnt be null"); } System.out.println("commuter:"+commuter); // updating only these three details. Mobile no. should not be updated // at all until unless deemed needed. if (isNonEmpty(name)) { commuter.setName(name); } if (isNonEmpty(email)) { commuter.setEmail(email); } if (isNonEmpty(gender)) { commuter.setGender(gender); } if (isNonEmpty(password)) { commuter.setPassword(<PASSWORD>); } commuter.setStatus(status); commuter.setActive(active); return commuterDao.updateCommuter(commuter); } private boolean isNonEmpty(String s) { if (s != null && s.length() > 0) { return true; } return false; } public boolean updateCommuterPassword(int commuter_id, String password) { Commuter commuter = getCommuterById(commuter_id); commuter.setPassword(<PASSWORD>); return commuterDao.updateCommuter(commuter); } private boolean updateCommuter(Commuter commuter) { return commuterDao.updateCommuter(commuter); } public boolean deleteCommuter(Commuter commuter) { System.out.println("deleting commuter:" + commuter.getCommuter_id()); return commuterDao.deleteCommuter(commuter); } public boolean deleteCommuter(int commter_id) { Commuter commuter = getCommuterById(commter_id); return commuterDao.deleteCommuter(commuter); } public boolean updateCommuterStatus(Commuter commuter, int status) { commuter.setStatus(status); return commuterDao.updateCommuter(commuter); } public List<Commuter> searchCommuters(String type, String str) { return commuterDao.searchCommuters(str, type); } public List<Commuter> searchCommuters(String columnName, Integer searchedValue) { return commuterDao.searchCommuters(columnName, searchedValue); } public ReturnCodes verifyCommuter(String mobile, int otpCode, boolean smsSendEnabled) { Commuter commuter = getCommuterByMobile(mobile); if (commuter == null) { System.out.println("Not able to find an entry for commeter mobile:" + mobile); return ReturnCodes.USER_NOT_EXIST; } if (commuter.getStatus() == UserStatusType.VERIFIED_ACTIVATED.getTypeCode()) { return ReturnCodes.USER_ALREADY_VERIFIED; } try { Commuter existingCommuterObject = commuter; Boolean alreadyActivated = existingCommuterObject.getAlready_activated(); ReturnCodes returnCode = activateCommuter(mobile, commuter.getCommuter_id(), otpCode, smsSendEnabled); if (returnCode.equals(ReturnCodes.USER_VERIFIED)) { try { System.out.println("Sending welcome signup message"); // Push notification sendWelcomeSignupMessage(commuter, commuter.getGcm_reg_id()); // Email // TODO: commenting it for now. //sendWelcomeMessageEmail(commuter); // if user is not already activated or it is false. System.out.println("alreadyActivated:"+alreadyActivated); boolean alreadyRegistrationExist = false; if (alreadyActivated == null || !alreadyActivated) { // as of now sending everytime a user registered with // us. he may be present in system before that. // SMS alreadyRegistrationExist = false; // taking all steps for referral int freeRidesGiven = takeActionForReferral(existingCommuterObject) + CommonConstants.DEFAULT_SIGNUP_FREE_RIDES; // sending welcome message sendWelcomeSignupMessageSMS(existingCommuterObject, freeRidesGiven, alreadyRegistrationExist, smsSendEnabled); } else { alreadyRegistrationExist = true; sendWelcomeSignupMessageSMS(existingCommuterObject, -1, alreadyRegistrationExist, smsSendEnabled); } } catch (Throwable e) { e.printStackTrace(); } return ReturnCodes.USER_VERIFIED; } else { System.out.println("Couldn't activate user."); return ReturnCodes.USER_VERIFICATION_FAILED; } } catch (Exception e) { e.printStackTrace(); return ReturnCodes.USER_VERIFICATION_FAILED; } } public int takeActionForReferral(Commuter userWhoGotReferred) { String referral_code_used = userWhoGotReferred.getReferral_code_used(); System.out.println("referral_code_used:" + referral_code_used + " by commuter:" + userWhoGotReferred.getName()); if (referral_code_used != null && referral_code_used.trim().length() > 0) { ReferralCode referralCode = referralCodeService.getReferralCodeByCode(referral_code_used); if (referralCode != null) { int userWhoReferredId = referralCode.getReferred_by(); int userWhoGotReferredId = userWhoGotReferred.getCommuter_id(); Commuter userWhoReferred = this.getCommuterById(userWhoReferredId); // Adding free rides this.creditFreeRidesToUsers(userWhoReferred, userWhoGotReferred); // adding referral history. this.addReferralHisotry(userWhoReferredId, userWhoGotReferredId); // check for upgrading to his one month free offer. this.checkForUpgradingToOneMonthFreeOffer(userWhoReferredId, userWhoGotReferredId); Integer freeRideReferredTo = getReferralFreeRidesReferredTo(); return freeRideReferredTo;//CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; } else { CorporateReferralCode corporateReferralCode = referralCodeService .getCorporateReferralCodeByCode(referral_code_used); if (corporateReferralCode != null) { System.out.println("user signing up with corporate referral code:" + referral_code_used); } else { System.out.println("referralCode object is null, mostly referral_code_used does not exist:" + referral_code_used); } } } else { System.out.println("referral_code_used is empty:" + referral_code_used); } // returning default signup credits. return 0; } public void addReferralHisotry(int userWhoReferredId, int userWhoGotReferredId) { ReferralTransactionInfo rtx = new ReferralTransactionInfo(); rtx.setReferred_by(userWhoReferredId); rtx.setReferred_to(userWhoGotReferredId); rtx.setReferred_to_redeemed_first_ride(false); this.referralTxService.insert(rtx); } public void checkForUpgradingToOneMonthFreeOffer(int userWhoReferredId, int userWhoGotReferredId) { List<ReferralTransactionInfo> referralsRedeemedFirstRide = referralTxService .getTransactionsByReferredBy(userWhoReferredId, true); System.out.println("referrals:"+referralsRedeemedFirstRide); if (referralsRedeemedFirstRide != null) { if (referralsRedeemedFirstRide.size() < CommonConstants.NUMBER_REFERRAL_1MONTH_FREE_RIDES) { System.out.println("Not taking any action as number of referrals are less"); // on 5th referral user should be upgraded to 1 month free ride. } else if (referralsRedeemedFirstRide.size() >= CommonConstants.NUMBER_REFERRAL_1MONTH_FREE_RIDES) { Account account = accountService.getAccountByCommuterId(userWhoReferredId); if (account != null && !account.isOne_month_free_activated()) { System.out.println("One month free is not activated for:" + userWhoGotReferredId + ", checking for pre-conditions"); boolean status = txService.cancelFreeRides(userWhoReferredId); if (status) { this.referralTxService.updateAccountForOneMonthFreeRide(userWhoReferredId); } else { System.out .println("User free rides cancelling failed--------------- so not updating his account for one month free ride"); } } else { System.out.println("One month free is already activated for:" + userWhoGotReferredId); } } // } else if (referrals.size() > CommonConstants.NUMBER_REFERRAL_1MONTH_FREE_RIDES) { // this.txService.systemRecharge(userWhoReferredId, CommonConstants.DEFAULT_CREDITS_AFTER_MAX_REFERRAL, 0, // TransactionStatus.SUCCESS, "REFERRAL_OF-" + userWhoGotReferredId); // } } } /** * * @param referredBy * : userWhoReferred * @param referredTo * : userWhoGotReferred */ private void creditFreeRidesToUsers(Commuter referredBy, Commuter referredTo) { // int credit_points_referred_by = 0; // int credit_points_referred_to = 0; // // int free_rides_referred_by = CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; // int free_rides_referred_to = CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; // // int userWhoReferredId = referredBy.getCommuter_id(); // int userWhoGotReferredId = referredTo.getCommuter_id(); // // System.out.println("Adding rides to "+referredBy.getCommuter_id()); creditFreeRidesOrCreditsToReferredByUser(referredBy, referredTo); // // adding a message that indicates that he referred which user. // String referral_of_transaction_desc = getReferralOfTxDesc(userWhoGotReferredId);//"REFERRAL_OF-"+referredTo.getCommuter_id(); // // List<ReferralTransactionInfo> allReferrals = referralTxService.getTransactionsByReferredBy(userWhoReferredId); // // boolean reachedMaxFreeRidesReferrals = false; // if (allReferrals != null) { // // after 5 // if (allReferrals.size() > CommonConstants.MAX_REFERRAL_FREE_RIDES) { // reachedMaxFreeRidesReferrals = true; // } else { // System.out.println("Referrals redeemed are :" + allReferrals.size() + " less than the no.of " // + CommonConstants.MAX_REFERRAL_FREE_RIDES); // } // } else { // System.out.println("No Referrals found "); // } // // if (!reachedMaxFreeRidesReferrals) { // // to the user who referred his friends // this.txService.systemRecharge(referredBy.getCommuter_id(), credit_points_referred_by, // free_rides_referred_by, TransactionStatus.SUCCESS, referral_of_transaction_desc); // } else { // // Adding only credits to the person, not the free rides. // this.txService.systemRecharge(userWhoReferredId, CommonConstants.DEFAULT_CREDITS_AFTER_MAX_REFERRAL, 0, // TransactionStatus.SUCCESS, "REFERRAL_OF-" + userWhoGotReferredId); // } // //==================Adding Rides to the Person who got referred======================= // System.out.println("Adding rides to "+referredTo.getCommuter_id()); // // // adding a message that indicates that he got referred by which user. // String referred_by_transaction_desc = getReferredByTxDesc(userWhoReferredId);//"REFERRED_BY-"+referredBy.getCommuter_id(); // // // to the user who got referred. The user who is registering now. // txService.systemRecharge(referredTo.getCommuter_id(), credit_points_referred_to, free_rides_referred_to, // TransactionStatus.SUCCESS, referred_by_transaction_desc); creditFreeRidesOrCreditsToReferredToUser(referredBy, referredTo); } private void creditFreeRidesOrCreditsToReferredByUser(Commuter referredBy, Commuter referredTo) { //boolean referral_credits_referred_by_enabled = this.isReferralCreditsToReferredByEnabled(); int referral_free_rides_referred_by = this.getReferralFreeRidesReferredBy(); int max_referral_free_rides = this.getMaxReferralFreeRides(); int credits_after_max_referral = this.getDefaultCreditsAfterMaxReferral(); // int free_rides_referred_by = CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; int free_rides_referred_by = referral_free_rides_referred_by; int credit_points_referred_by = this.getReferralFreeCreditsReferredBy(); int userWhoReferredId = referredBy.getCommuter_id(); int userWhoGotReferredId = referredTo.getCommuter_id(); // adding a message that indicates that he referred which user. String referral_of_transaction_desc = getReferralOfTxDesc(userWhoGotReferredId);// "REFERRAL_OF-"+referredTo.getCommuter_id(); List<ReferralTransactionInfo> allReferrals = referralTxService.getTransactionsByReferredBy(userWhoReferredId); boolean reachedMaxFreeRidesReferrals = false; if (allReferrals != null) { // after 5 if (allReferrals.size() >= max_referral_free_rides) { reachedMaxFreeRidesReferrals = true; } else { System.out.println("Referrals redeemed are :" + allReferrals.size() + " less than the no.of " + max_referral_free_rides); } } else { System.out.println("No Referrals found "); } if (!reachedMaxFreeRidesReferrals) { // to the user who referred his friends this.txService.systemRecharge(userWhoReferredId, credit_points_referred_by, free_rides_referred_by, TransactionStatus.SUCCESS, referral_of_transaction_desc); } else { // Adding only credits to the person, not the free rides. this.txService.systemRecharge(userWhoReferredId, credits_after_max_referral, 0, TransactionStatus.SUCCESS, "REFERRAL_OF-" + userWhoGotReferredId); } } private Integer getMaxReferralFreeRides() { Integer value = settingsService.getDashBoardSettings().getMax_referral_free_rides(); if (value == null) { return CommonConstants.MAX_REFERRAL_FREE_RIDES; } return value; } private Integer getDefaultCreditsAfterMaxReferral() { Integer value = settingsService.getDashBoardSettings().getCredits_after_max_referral(); if (value == null) { return CommonConstants.DEFAULT_CREDITS_AFTER_MAX_REFERRAL; } return value; } private Integer getReferralFreeRidesReferredBy() { Integer value = settingsService.getDashBoardSettings().getReferral_free_rides_referred_by(); if (value == null) { return CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; } return value; } private Integer getReferralFreeRidesReferredTo() { Integer value = settingsService.getDashBoardSettings().getReferral_free_rides_referred_to(); if (value == null) { return CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; } return value; } private Integer getReferralFreeCreditsReferredBy() { Integer value = settingsService.getDashBoardSettings().getReferral_free_credits_referred_by(); if (value == null) { return CommonConstants.DEFAULT_REFERRAL_FREE_CREDITS; } return value; } private Integer getReferralFreeCreditsReferredTo() { Integer value = settingsService.getDashBoardSettings().getReferral_free_credits_referred_to(); if (value == null) { return CommonConstants.DEFAULT_REFERRAL_FREE_CREDITS; } return value; } private Boolean isReferralCreditsToReferredByEnabled() { Boolean value = settingsService.getDashBoardSettings().getReferral_free_credits_referred_by_enabled(); if (value == null) { return false; } return value; } private Boolean isReferralCreditsToReferredToEnabled() { Boolean value = settingsService.getDashBoardSettings().getReferral_free_credits_referred_to_enabled(); if (value == null) { return false; } return value; } private void creditFreeRidesOrCreditsToReferredToUser(Commuter referredBy, Commuter referredTo){ //boolean referral_credits_referred_to_enabled = this.isReferralCreditsToReferredToEnabled(); int credit_points_referred_to = this.getReferralFreeCreditsReferredTo(); int referral_free_rides_referred_to = this.getReferralFreeRidesReferredTo(); //int free_rides_referred_to = CommonConstants.DEFAULT_REFERRAL_FREE_RIDES; int free_rides_referred_to = referral_free_rides_referred_to; int userWhoReferredId = referredBy.getCommuter_id(); int userWhoGotReferredId = referredTo.getCommuter_id(); //==================Adding Rides to the Person who got referred======================= System.out.println("Adding rides to "+userWhoGotReferredId); // adding a message that indicates that he got referred by which user. String referred_by_transaction_desc = getReferredByTxDesc(userWhoReferredId);//"REFERRED_BY-"+referredBy.getCommuter_id(); // // if only giving credits are enabled then we will give only credits not // // free rides. // // in other condition we will free rides, not credits. // if (referral_credits_referred_to_enabled) { // // } // to the user who got referred. The user who is registering now. txService.systemRecharge(userWhoGotReferredId, credit_points_referred_to, free_rides_referred_to, TransactionStatus.SUCCESS, referred_by_transaction_desc); } private String getReferredByTxDesc(int userWhoReferredId) { return "REFERRED_BY-" + userWhoReferredId; } private String getReferralOfTxDesc(int userWhoGotReferredId) { return "REFERRAL_OF-" + userWhoGotReferredId; } public void sendWelcomeMessageEmail(Commuter commuter){ EmailDTO emailObj = new EmailDTO(); emailObj.setTo(new String[]{commuter.getEmail()}); emailObj.setSubject(commuter.getName() + ", Welcome to EasyCommute"); emailObj.setText(commuter.getName() + ", Thank you for signing up for EasyCommute"); EmailResponse emailResp = emailProvider.sendEmail(emailObj); System.out.println("emailResp:" + emailResp); } // we are taking mobile no. in consideration, as he might be trying to regenerate after changing his mobile no. // so if we get mobile no. public ReturnCodes regenrateOTP(String mobile, int commuter_id, boolean smsSendEnabled) { Commuter c = getCommuterById(commuter_id); if (c == null) { System.out.println("Not able to find an entry for commeter id:" + commuter_id); if (mobile != null) { c = getCommuterByMobile(mobile); if (c == null) { System.out.println("Not able to find an entry for commeter mobile:" + mobile); return ReturnCodes.USER_NOT_EXIST; } } else { System.out.println("Not able to find an entry for commeter id:" + commuter_id + " and mobile no is null in request parameter"); return ReturnCodes.USER_NOT_EXIST; } } // if user already exist and activated, we shouldnt goof up ourself that we allow him to change his mobile no. if (c != null && c.getStatus() == 1) { System.out.println("User already exist, again generating an otp, in regenrateOTP"); // here it shouldnt be the mobile no that we are getting in request. // it should the mobile no. that we have. generateAndSendOTP(c.getMobile(), c.getCommuter_id(), c.getName(), smsSendEnabled); // Since User exist, generating an another OTP c.setStatus(UserStatusType.REGISTED_NOT_ACTIVATED.getTypeCode()); boolean status = commuterDao.updateCommuter(c); if (status) { System.out.println("Commuter id:" + c.getCommuter_id() + " inactivated as new OTP generated in regenrateOTP"); } else { System.out.println("Failed to update in DB for commuter id:" + c.getCommuter_id() + " inactivated as new OTP generated"); } return ReturnCodes.USER_ALREADY_EXIST; } //================ user shoudnt reach here if he is already activated.============= // as that will cause him to allow to change the mobile no. boolean updated = false; // if the mobile no. we are getting in request is not empty and its different then previous no. entered. if (mobile != null && !(mobile.equals(c.getMobile()))) { c.setMobile(mobile); updated = updateCommuter(c); if (updated) { System.out .println("Updating his new mobile no. in system and generated an OTP on new number: updated status: success"); } else { System.out .println("Updating his new mobile no. in system and generated an OTP on new number: updated status: failed"); } } else { mobile = c.getMobile(); } System.out.println("User already exist but not activated so again generating an otp"); generateAndSendOTP(mobile, commuter_id, c.getName(), smsSendEnabled); return ReturnCodes.USER_EXIST_OTP_GENERATED; } public ReturnCodes activateCommuter(String mobile, int commuter_id, int otpCode, boolean smsSendEnabled) { // Commuter commuter = commuterDao.activateCommuter(commuter_id, // otpCode); boolean status = false; // if (commuter != null) { // status = true; // } else { // status = false; // } Object[] arr = commuterDao.getCommuterWithOTPCode(commuter_id); System.out.println("arr:" + arr); if (arr == null) { throw new IllegalArgumentException("It seems commuter_id is not available"); } Commuter commuter = (Commuter) arr[0]; SMSCode smsCode = (SMSCode) arr[1]; System.out.println("Commuter:" + commuter); System.out.println("smsCode:" + smsCode); if (commuter != null && smsCode != null) { int code = smsCode.getCode(); if (code == otpCode) { Timestamp sentTime = smsCode.getCreated_at(); long sentTimeVal = sentTime.getTime(); Date currentTime = new Date(); long currentTimeVal = currentTime.getTime(); long diff = TimeUnit.MILLISECONDS.toMinutes(currentTimeVal) - TimeUnit.MILLISECONDS.toMinutes(sentTimeVal); if (diff < 30) { status = true; } else { status = false; System.out.println("Code expired for commuter_id:" + commuter_id + "--diff:" + diff); generateAndSendOTP(mobile, commuter_id, commuter.getName(), smsSendEnabled); return ReturnCodes.USER_OTP_EXPIRED_OTP_GENERATED; } } } else { System.out.println("Commuter:" + commuter); System.out.println("smsCode:" + smsCode); } if (status) { Commuter existingDetails = commuterDao.getCommuter(commuter_id); Boolean alreadyActivated = existingDetails.getAlready_activated(); boolean activated = activateCommuterStatus(existingDetails); System.out.println("commuter:" + commuter.getCommuter_id() + "--" + " activated successfully"); System.out.println("is alreadyActivated:"+alreadyActivated +" ---"+commuter.getCommuter_id() ); if (activated) { // credit free rides // If user is already activated (if he tries to remove the app data and try again and agin), then // ensuring that system is not giving him credits again and again. // Read more the comment on the field here : => {@link: Commuter.already_activated } if (alreadyActivated == null || !alreadyActivated) { this.creditFreeRides(commuter_id, TransactionStatus.SUCCESS); } else { System.out.println("User was already there in system, so not giving him again credits"); } System.out.println("removing entry for commuter:" + commuter.getCommuter_id()); boolean deleted = commuterDao.deleteSMSCodeByCommuterId(commuter_id); if (deleted) { System.out.println("Removed entry for existing sms codes for commuter:" + commuter_id); } return ReturnCodes.USER_VERIFIED; } else { return ReturnCodes.USER_VERIFICATION_FAILED; } } else { return ReturnCodes.USER_INVALID_OTP; //throw new ServiceException("Invalid OTP"); } } private void creditFreeRides(int commuter_id, TransactionStatus status) { if (CommonConstants.SIGNUP_CREDIT_PROMOTION_SCHEME_ENABLED) { try { transactionService.systemRecharge(commuter_id, CommonConstants.DEFAULT_SIGNUP_POINTS, CommonConstants.DEFAULT_SIGNUP_FREE_RIDES, TransactionStatus.SUCCESS, "SIGNUP CREDIT"); } catch (Exception e) { e.printStackTrace(); } } } // TODO: improve it as we need to update only a single field. // Can we write direct query for it. public boolean activateCommuterStatus(Commuter commuter) { commuter.setStatus(UserStatusType.VERIFIED_ACTIVATED.getTypeCode()); commuter.setVerified_at(new Timestamp(System.currentTimeMillis())); commuter.setAlready_activated(true); boolean success = commuterDao.updateEntity(commuter); return success; } public boolean isCommuterExist(String mobile) { Commuter c1 = getCommuterByMobile(mobile); if (c1 != null) { return true; } return false; } public BigInteger getCommutersCount() { return commuterDao.getCommutersCount(); } public int[] getActiveAndVerifiedCommuterIds() { List<Commuter> commuters = this.findAllActiveAndVerified(); int[] newIds = new int[commuters.size()]; for (int i = 0; i < commuters.size(); i++) { newIds[i] = commuters.get(i).getCommuter_id(); } return newIds; } public boolean validateUserByPassword(String mobile, String password) { Commuter c = getCommuterByMobile(mobile); if (c == null) { return false; } String password_db = c.getPassword(); // if there is no password in db. if (password_db == null) { return false; } else { // if there is password already set then compare. String originalPassword = PasswordEncrypter.decryptText(password_db); if (password != null && password.equals(originalPassword)) { return true; } } return false; } public boolean regenrateOTP(String mobile) { Commuter c = getCommuterByMobile(mobile); if (c == null) { return false; } boolean smsSendEnabled = true; generateAndSendOTP(c.getMobile(), c.getCommuter_id(), c.getName(), smsSendEnabled); return true; } public ReturnCodes validateUserByOTP(String mobile, Integer otpCode) { Commuter c = getCommuterByMobile(mobile); if (c == null) { return null; } int commuter_id = c.getCommuter_id(); boolean smsSendEnabled = true; // Commuter commuter = commuterDao.activateCommuter(commuter_id, // otpCode); boolean status = false; // if (commuter != null) { // status = true; // } else { // status = false; // } Object[] arr = commuterDao.getCommuterWithOTPCode(commuter_id); System.out.println("arr:" + arr); if (arr == null) { throw new IllegalArgumentException("It seems commuter_id is not available"); } Commuter commuter = (Commuter) arr[0]; SMSCode smsCode = (SMSCode) arr[1]; System.out.println("Commuter:" + commuter); System.out.println("smsCode:" + smsCode); if (commuter != null && smsCode != null) { int code = smsCode.getCode(); if (code == otpCode) { Timestamp sentTime = smsCode.getCreated_at(); long sentTimeVal = sentTime.getTime(); Date currentTime = new Date(); long currentTimeVal = currentTime.getTime(); long diff = TimeUnit.MILLISECONDS.toMinutes(currentTimeVal) - TimeUnit.MILLISECONDS.toMinutes(sentTimeVal); if (diff < 30) { status = true; } else { status = false; System.out.println("Code expired for commuter_id:" + commuter_id + "--diff:" + diff); generateAndSendOTP(mobile, commuter_id, commuter.getName(), smsSendEnabled); return ReturnCodes.USER_OTP_EXPIRED_OTP_GENERATED; } } } else { System.out.println("Commuter:" + commuter); System.out.println("smsCode:" + smsCode); } if (status) { System.out.println("removing entry for commuter:" + commuter.getCommuter_id()); boolean deleted = commuterDao.deleteSMSCodeByCommuterId(commuter_id); if (deleted) { System.out.println("Removed entry for existing sms codes for commuter:" + commuter_id); } return ReturnCodes.USER_VERIFIED; } else { return ReturnCodes.USER_VERIFICATION_FAILED; } } } <file_sep>package com.main.sts.entities; import java.sql.Timestamp; import java.util.Comparator; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Entity; @Entity @Table(name = "suggest_routes") public class SuggestRoute implements Comparator { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String from_stop; private String to_stop; private Timestamp created_at; // can be null for backward compatibility private Integer commuter_id; private Integer start_time_hour; private Integer start_time_minutes; private Integer end_time_hour; private Integer end_time_minutes; public int getId() { return id; } public String getFrom_stop() { return from_stop; } public void setFrom_stop(String from_stop) { this.from_stop = from_stop; } public String getTo_stop() { return to_stop; } public void setTo_stop(String to_stop) { this.to_stop = to_stop; } public void setId(int id) { this.id = id; } public Timestamp getCreated_at() { return created_at; } public void setCreated_at(Timestamp created_at) { this.created_at = created_at; } public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getStart_time_hour() { return start_time_hour; } public void setStart_time_hour(Integer start_time_hour) { this.start_time_hour = start_time_hour; } public Integer getStart_time_minutes() { return start_time_minutes; } public void setStart_time_minutes(Integer start_time_minutes) { this.start_time_minutes = start_time_minutes; } public Integer getEnd_time_hour() { return end_time_hour; } public void setEnd_time_hour(Integer end_time_hour) { this.end_time_hour = end_time_hour; } public Integer getEnd_time_minutes() { return end_time_minutes; } public void setEnd_time_minutes(Integer end_time_minutes) { this.end_time_minutes = end_time_minutes; } @Override public int compare(Object o1, Object o2) { SuggestRoute r1 = (SuggestRoute) o1; SuggestRoute r2 = (SuggestRoute) o2; if (r1.id > r2.id) return 1; else return 0; } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.encoding.Md4PasswordEncoder; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.AdminEmails; import com.main.sts.entities.DashboardSettings; import com.main.sts.service.AdminEmailService; import com.main.sts.service.DashBoardSettingsService; import com.main.sts.util.MD5PassEncryptionClass; @Controller @RequestMapping(value = "/school_admin/settings") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") public class DashBoardSettingsController { private static final Logger logger = Logger.getLogger(DashBoardSettingsController.class); @Autowired MD5PassEncryptionClass password; @Autowired private AdminEmailService adminEmailService; @Autowired private DashBoardSettingsService boardSettingsService; @RequestMapping(value = "/view") public ModelAndView preferences(ModelAndView model, HttpServletRequest request) { // //System.out.println("insid preferences"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); model.setViewName("/school_admin/settings"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("dashBoardSettings", boardSettingsService.getDashBoardSettings()); model.addObject("emails", adminEmailService.getAllMails()); DashboardSettings preferences = boardSettingsService.getDashBoardSettings(); String plain = password.DecryptText(preferences.getSmtp_password()); model.addObject("smtp_password", plain); /* * To check which role use is logged in */ if (request.isUserInRole("ROLE_ADMIN")) { model.addObject("login_role", "ROLE_ADMIN"); } return model; } @RequestMapping(value = "/update", method = RequestMethod.POST) public ModelAndView updatepreferenceAction(ModelAndView model, HttpServletRequest request, @ModelAttribute DashboardSettings dashboardSettings) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // //System.out.println("insdie updatepreferences"); model.setViewName("redirect:/school_admin/settings/view"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); boardSettingsService.updateSettings(dashboardSettings); logger.info("Dashboard settings have been updated"); return model; } @RequestMapping(value = "/adminemail/add") public @ResponseBody String addEmailsToPreferences(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("adminPreferences", boardSettingsService.getDashBoardSettings()); String email = request.getParameter("email"); adminEmailService.addEmail(email); logger.info("Admin Email [ " + email + " ] has been added"); return "/sts/school_admin/settings/view"; } /* * @RequestMapping(value = "/adminemail/update") public ModelAndView * updateEmail(ModelAndView model, HttpServletRequest request) { * Authentication auth = * SecurityContextHolder.getContext().getAuthentication(); // * //System.out.println("insdie updatepreferences"); * model.setViewName("redirect:/school_admin/settings/view"); DateFormat * formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", * formatter.format(new Date())); model.addObject("login_name", * auth.getName()); // //System.out.println("Admin "+admin); * AdminPreferences admin_profile = * adminPreferencesDaoImpl.getAdminPreferences(); * model.addObject("adminPreferences", * adminPreferencesDaoImpl.getAdminPreferences()); return model; } */ @RequestMapping(value = "/adminemail/delete") public ModelAndView deleteEmail(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); // System.out.println("insdie updatepreferences"); model.setViewName("redirect:/school_admin/settings/view"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); Integer id = Integer.parseInt(request.getParameter("id")); AdminEmails adminEmails = adminEmailService.getMail(id); logger.info("Admin Email [ " + adminEmails.getEmail() + " ] has been deleted"); adminEmailService.deleteEmail(id); return model; } } <file_sep>package com.main.sts.util; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component; @Component public class RolesUtility { public String getRole(HttpServletRequest request) { if (request.isUserInRole("ROLE_ADMIN")) { return "ROLE_ADMIN"; } else if (request.isUserInRole("ROLE_GUEST")) { return "ROLE_GUEST"; } else return "ROLE_GUEST"; } } <file_sep>$(document).ready(function() { $("#loading").show(); load(); setInterval(function() { $("#loading").show(); load(); }, 4000); }); function load(){ //alert($("#session").val()); $('[data-toggle]').popover('hide'); $.ajax({ url:"bus/getBusPageData", type:"POST", data:"bus_id="+$("#bus_id").val()+"&trip_id="+$("#session").val(), success:function(res){ res=$.trim(res); //alert(res); if(res=="none"){ //alert(" I am none"); $("#loading").hide(); } else{ var data=res.split("+"); var obj = JSON.parse(data[5]); //var absent_students = JSON.parse(data[7]); $("#bus_lice_number").empty().append('Bus: &nbsp;&nbsp;<font color="sienna">'+data[3]+'</font>'); $("#no_of_students").empty().append('Subscribers in bus: &nbsp;&nbsp;<font color="sienna">'+data[4]+'</font>'); if(data[1]=="ontime"){ $("#bus_status").empty().append('Status: &nbsp;&nbsp;<span class="label label-success">Ontime</span>'); } if(data[1]=="late"){ $("#bus_status").empty().append('Status: &nbsp;&nbsp;<span class="label label-warning">Late</span>'); } if(data[1]=="verylate"){ $("#bus_status").empty().append('Status: &nbsp;&nbsp;<span class="label label-danger">Very Late</span>'); } $("#bus_current_stop").empty().append('Current Stop:&nbsp;&nbsp;<font color="sienna">'+data[2]+'</font>'); /* var res="none"; if(json[i].arrived_time!="none") res = json[i].arrived_time.split(" ");*/ $("#bus_current_arrived").empty().append('Arrived Time:&nbsp;&nbsp;<font color="sienna">'+data[0]+'</font>'); $("#tbody_students").empty(); var append=""; for(var i=0;i<obj.length;i++){ //alert(obj[i]); var in_stop = ""; var out_stop = ""; var in_stop_time = ""; var out_stop_time = ""; var subscriber_boarded_wrong_stop_inbound = obj[i].subscriber_boarded_wrong_stop_inbound; var subscriber_boarded_wrong_stop_outbound = obj[i].subscriber_boarded_wrong_stop_outbound; //alert(subscriber_boarded_wrong_stop_inbound); if(subscriber_boarded_wrong_stop_inbound=="none" || subscriber_boarded_wrong_stop_inbound == null) in_stop ='<span class="label label-success">'+obj[i].in_stop+'</span>'; else{ /* in_stop="<span class='label label-warning bs-popover' data-trigger='hover' data-placement='top' data-content='Popover body goes here! Popover body goes here!' data-original-title='Popover at top'>" +obj[i].in_stop +"</span>";*/ var sp=subscriber_boarded_wrong_stop_inbound.split("*"); //alert(sp); in_stop='<span class="label label-warning bs-popover" data-html="true" title="Subscriber Boarded Bus at Wrong Stop" '+ ' data-container="body" data-toggle="popover" data-placement="top"'+ ' data-content="Actual Stop: <font size=3><b> '+sp[1]+'</b></font> ">'+obj[i].in_stop '</span>'; //alert(subscriber_boarded_wrong_stop_inbound); } //alert(subscriber_boarded_wrong_stop_outbound); if(subscriber_boarded_wrong_stop_outbound=="none" || subscriber_boarded_wrong_stop_outbound ==null){ //alert(subscriber_boarded_wrong_stop_outbound); if(obj[i].out_stop!="none") out_stop='<span class="label label-success">'+obj[i].out_stop+'</span>'; else out_stop=obj[i].out_stop; } else{ //alert(subscriber_boarded_wrong_stop_outbound); var sp=subscriber_boarded_wrong_stop_outbound.split("*"); out_stop='<span class="label label-danger bs-popover" data-html="true" title="Subscriber Getoff Bus at Wrong Stop" '+ ' data-container="body" data-toggle="popover" data-placement="top"'+ ' data-content="Actual Stop: <font size=3><b> '+sp[1]+'</b></font> ">'+obj[i].out_stop '</span>'; //alert(subscriber_boarded_wrong_stop_inbound); } in_stop_time = obj[i].in_time; out_stop_time = obj[i].out_time; var subscriber_boarded_wrong_bus=obj[i].subscriber_boarded_wrong_bus; var subscriber_boarded_wrong_trip=obj[i].subscriber_boarded_wrong_trip; if(subscriber_boarded_wrong_bus!="none"){ append = append + "<tr>" + "<td>"+'<span class="label label-danger bs-popover" data-html="true" title="Student Boarded Wrong Bus" '+ ' data-container="body" data-toggle="popover" data-placement="top"'+ ' data-content="Assigned Bus: <font size=3><b> '+subscriber_boarded_wrong_bus.split(":")[0]+'</b></font> &nbsp;&nbsp;Boarded Bus: <font size=3><b> '+subscriber_boarded_wrong_bus.split(":")[1]+'</b></font> ">' + obj[i].subscriber_name+ "</td>"; } else if(subscriber_boarded_wrong_bus=="none" && subscriber_boarded_wrong_trip!="none"){ append = append + "<tr>" + "<td>"+'<span class="label label-danger bs-popover" data-html="true" title="Student Taken different Trip" '+ ' data-container="body" data-toggle="popover" data-placement="top"'+ ' data-content="Assigned Trip: <font size=3><b> '+subscriber_boarded_wrong_trip.split(":")[0]+'</b></font> &nbsp;&nbsp;Boarded Trip: <font size=3><b> '+subscriber_boarded_wrong_trip.split(":")[1]+'</b></font> ">' + obj[i].subscriber_name+ "</td>"; } else{ append = append + "<tr>" + "<td>" + obj[i].subscriber_name+ "</td>"; } append = append + "<td>" + in_stop + "</td>" + "<td>" + in_stop_time + "</td>" + "<td>" + out_stop + "</td>" + "<td>" + out_stop_time + "</td>" + "</tr>" ; } /*for(var j=0;j<absent_students.length;j++){ var stop_name; if(data[6]=="Drop Off"){ stop_name=absent_students[j].stop_name_fromschool; } if(data[6]=="Pick Up"){ stop_name=absent_students[j].stop_name_fromhome; } var absent='<span class="label label-danger bs-popover" data-html="true" title="Student Not Boarded Bus" '+ ' data-container="body" data-toggle="popover" data-placement="top"'+ ' data-content="At Stop: <font size=3><b> '+stop_name+' </b></font> "> Absent</span>'; append = append + "<tr>" + "<td> "+absent_students[j].first_name +" "+absent_students[j].last_name+"</td>" +"<td>"+absent+" </td>" +"<td> </td>" +"<td> </td>" +"<td> </td>" + "</tr>" ; }*/ $("#tbody_students").append(append); } $("[data-toggle='popover']").popover({ trigger: "hover" }); $("#loading").hide(); } }); } <file_sep>package com.main.sts.dto; import java.io.Serializable; public class FeedbackDTO implements Serializable{ Integer commuter_id; Integer trip_id; Integer booking_id; Integer rating_points; String reason; String concern; public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public Integer getTrip_id() { return trip_id; } public void setTrip_id(Integer trip_id) { this.trip_id = trip_id; } public Integer getBooking_id() { return booking_id; } public void setBooking_id(Integer booking_id) { this.booking_id = booking_id; } public Integer getRating_points() { return rating_points; } public void setRating_points(Integer rating_points) { this.rating_points = rating_points; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getConcern() { return concern; } public void setConcern(String concern) { this.concern = concern; } }<file_sep>package com.main.sts.dto.response; import java.io.Serializable; public class OfferCheck implements Serializable { public String offer_message; public boolean enabled_offer_check; public String getOffer_message() { return offer_message; } public void setOffer_message(String offer_message) { this.offer_message = offer_message; } public boolean isEnabled_offer_check() { return enabled_offer_check; } public void setEnabled_offer_check(boolean enabled_offer_check) { this.enabled_offer_check = enabled_offer_check; } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.RfidCards; @Repository public class RfidDao extends BaseDao { public List<RfidCards> listRfids(String type) { String queryStr = "from RfidCards r where r.type = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, type); return (List<RfidCards>) getRecords(RfidCards.class, queryStr, parameters, 0); } public List<RfidCards> listAvailableRfids(String type, int rfid_status) { String queryStr = "from RfidCards r where r.type = ? and r.available = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, type); parameters.put(1, rfid_status); return (List<RfidCards>) getRecords(RfidCards.class, queryStr, parameters, 0); } public RfidCards getRfid(String rfid_number) { String queryStr = "from RfidCards u where u.rfid_number = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, rfid_number); return getSingleRecord(RfidCards.class, queryStr, parameters); } public RfidCards getRfid(int id) { String queryStr = "from RfidCards u where u.id = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); return getSingleRecord(RfidCards.class, queryStr, parameters); } public void insertRfid(RfidCards cards) { insertEntity(cards); } public void updateRfidNumber(String current_rfid, String new_rfid) { RfidCards rfidCards = getRfid(current_rfid); rfidCards.setRfid_number(new_rfid); updateEntity(rfidCards); } public void deleteRfid(int id) { String queryStr = "from RfidCards r where r.id = ?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, id); RfidCards cards = getSingleRecord(RfidCards.class, queryStr, parameters); deleteEntity(cards); } public List<RfidCards> searchRfids(String str, String type) { Map<String, Object> restrictions = new HashMap<String, Object>(); restrictions.put("type", type); restrictions.put("rfid_number", "%" + str + "%"); return searchRecords(RfidCards.class, restrictions); } public void updateRfid(RfidCards cards) { updateEntity(cards); /* * Session session = openSession(); Transaction tx = null; try { tx = * session.beginTransaction(); * * session.update(cards); tx.commit(); } catch (HibernateException e) { * if (tx != null) tx.rollback(); e.printStackTrace(); } finally { * session.close(); } */ } } <file_sep>package com.ec.eventserver.models; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "daily_bus_stops") public class DailyBusStops { @Id @GeneratedValue private int id; private int trip_id; private int routestop_id; private Date running_date; private String expected_time; private String arrived_time; private Double latitude; private Double longitude; private boolean is_stop_out_of_range; private boolean is_eta_sent = false; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTrip_id() { return trip_id; } public void setTrip_id(int trip_id) { this.trip_id = trip_id; } public int getRoutestop_id() { return routestop_id; } public void setRoutestop_id(int routestop_id) { this.routestop_id = routestop_id; } public Date getRunning_date() { return running_date; } public void setRunning_date(Date running_date) { this.running_date = running_date; } public String getExpected_time() { return expected_time; } public void setExpected_time(String expected_time) { this.expected_time = expected_time; } public String getArrived_time() { return arrived_time; } public void setArrived_time(String arrived_time) { this.arrived_time = arrived_time; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public boolean isIs_stop_out_of_range() { return is_stop_out_of_range; } public void setIs_stop_out_of_range(boolean is_stop_out_of_range) { this.is_stop_out_of_range = is_stop_out_of_range; } public boolean isIs_eta_sent() { return is_eta_sent; } public void setIs_eta_sent(boolean is_eta_sent) { this.is_eta_sent = is_eta_sent; } @Override public String toString() { return "DailyBusStops [id=" + id + ", trip_id=" + trip_id + ", routestop_id=" + routestop_id + ", date=" + running_date + ", expected_time=" + expected_time + ", arrived_time=" + arrived_time + ", latitude=" + latitude + ", longitude=" + longitude + ", is_stop_out_of_range=" + is_stop_out_of_range + ", is_eta_sent=" + is_eta_sent + "]"; } } <file_sep>package com.main.sts.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.AccountDao; import com.main.sts.dao.sql.ReferralTransactionDao; import com.main.sts.entities.ReferralTransactionInfo; @Service("referralTransactionService") public class ReferralTransactionService { @Autowired private ReferralTransactionDao referralAccountDao; @Autowired private AccountDao accountDao; // @Autowired // private TransactionDao transactionDao; public List<ReferralTransactionInfo> findAll() { return referralAccountDao.findAll(); } public ReferralTransactionInfo getAccount(int account_id) { return referralAccountDao.fetchAccount(account_id); } public ReferralTransactionInfo getAccountByCommuterId(int commuter_id) { return referralAccountDao.fetchAccountByCommuterId(commuter_id); } public void insert(ReferralTransactionInfo entity) { entity.setCreated_at(new Date()); referralAccountDao.insertEntityAndGetId(entity); } public ReferralTransactionInfo getTransactionById(int tx_id) { return referralAccountDao.findTransactionById(tx_id); } public List<ReferralTransactionInfo> getTransactionsByCommuterId(int referred_by, Integer offset, Integer limit) { return referralAccountDao.findTransactionByReferredBy(referred_by, offset, limit); } public List<ReferralTransactionInfo> getTransactionsByReferredBy(int referred_by) { return referralAccountDao.findTransactionByReferredBy(referred_by); } public List<ReferralTransactionInfo> getTransactionsByReferredBy(int referred_by, boolean referred_to_redeemed_first_ride) { return referralAccountDao.findTransactionByReferredBy(referred_by, referred_to_redeemed_first_ride); } public ReferralTransactionInfo findLastTransactionByCommuterId(int commuter_id) { return referralAccountDao.findLastTransactionByCommuterId(commuter_id); } public void updateAccountForOneMonthFreeRide(int userWhoReferredId) { accountDao.updateAccountForOneMonthFreeRide(userWhoReferredId); } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Roles; @Repository public class UserRoleDao extends BaseDao { public void insertRole(Roles role) { insertEntity(role); } public void updateRole(Roles role) { updateEntity(role); } public List<Roles> getRoles() { return getAllRecords(Roles.class); } public Roles getRoleByRoleName(String role_name) { String querString = "from Roles r where r.role_name =?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, role_name); return getSingleRecord(Roles.class, querString, parameters); } public Roles getRole(int role_id) { String queryStr = "from Roles r where r.role_id =?"; Map<Integer, Object> parameter = new HashMap<Integer, Object>(); parameter.put(0, role_id); return getSingleRecord(Roles.class, queryStr, parameter); } public void deleteRole(Roles role) { deleteEntity(role); } } <file_sep>package com.main.sts.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.SavedRoutes; import com.main.sts.service.SavedRoutesService; @Controller @RequestMapping(value = "/school_admin/saved_routes") public class SavedRoutesWebController { @Autowired private SavedRoutesService savedRoutesService; @RequestMapping(value = "/list", method = RequestMethod.GET) public ModelAndView savedRoutesHomePage(ModelAndView model, HttpServletRequest request){ List<SavedRoutes> savedRoutes = savedRoutesService.getAllSavedRoutes(); for(SavedRoutes savedRoute : savedRoutes) { System.out.println(savedRoute); } model.setViewName("/school_admin/saved_routes/list"); model.addObject("saved_routes", savedRoutes); return model; } } <file_sep>package com.main.sts.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "price_fare") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "price_fare") public class BusFarePriceEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "price_fare_id_seq_gen") @SequenceGenerator(name = "price_fare_id_seq_gen", sequenceName = "price_fare_id_seq") private int fare_id; @OneToOne(targetEntity = Stops.class) @JoinColumn(name = "source_stop_id", referencedColumnName = "id", insertable = false, updatable = false) public Stops source_stop; @OneToOne(targetEntity = Stops.class) @JoinColumn(name = "dest_stop_id", referencedColumnName = "id", insertable = false, updatable = false) public Stops dest_stop; private int source_stop_id; private int dest_stop_id; @Column(name = "actual_fare") private int actual_fare; // private int actual_fare = charged_fare; @Column(name = "charged_fare") private int charged_fare; private int auto_fare, bus_fare; private String distance; private String time_duration; private Boolean discounted_fare_enabled = false; private Integer discounted_fare = 0; private Date created_at; private Date updated_at; public int getFare_id() { return fare_id; } public void setFare_id(int fare_id) { this.fare_id = fare_id; } public int getSource_stop_id() { return source_stop_id; } public void setSource_stop_id(int source_stop_id) { this.source_stop_id = source_stop_id; } public int getDest_stop_id() { return dest_stop_id; } public void setDest_stop_id(int dest_stop_id) { this.dest_stop_id = dest_stop_id; } public int getAuto_fare() { return auto_fare; } public void setAuto_fare(int auto_fare) { this.auto_fare = auto_fare; } public int getBus_fare() { return bus_fare; } public void setBus_fare(int bus_fare) { this.bus_fare = bus_fare; } public Stops getSource_stop() { return source_stop; } public void setSource_stop(Stops source_stop) { this.source_stop = source_stop; } public Stops getDest_stop() { return dest_stop; } public void setDest_stop(Stops dest_stop) { this.dest_stop = dest_stop; } public int getActual_fare() { return actual_fare; } public void setActual_fare(int actual_fare) { this.actual_fare = actual_fare; } public int getCharged_fare() { return charged_fare; } public void setCharged_fare(int charged_fare) { this.charged_fare = charged_fare; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public String getTime_duration() { return time_duration; } public void setTime_duration(String time_duration) { this.time_duration = time_duration; } public Boolean getDiscounted_fare_enabled() { return discounted_fare_enabled; } public void setDiscounted_fare_enabled(Boolean discounted_fare_enabled) { this.discounted_fare_enabled = discounted_fare_enabled; } public Integer getDiscounted_fare() { return discounted_fare; } public void setDiscounted_fare(Integer discounted_fare) { this.discounted_fare = discounted_fare; } public Date getCreated_at() { return created_at; } public void setCreated_at(Date created_at) { this.created_at = created_at; } public Date getUpdated_at() { return updated_at; } public void setUpdated_at(Date updated_at) { this.updated_at = updated_at; } @Override public String toString() { return "BusFarePriceEntity [fare_id=" + fare_id + ", source_stop_id=" + source_stop_id + ", dest_stop_id=" + dest_stop_id + ", fare=" + charged_fare + ", auto_fare=" + auto_fare + ", bus_fare=" + bus_fare + "]"; } } <file_sep>package com.main.sts.controllers; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.common.CommonConstants.TripStatus; import com.main.sts.common.CommonConstants.VehicleStatus; import com.main.sts.entities.Buses; import com.main.sts.entities.DailyBusCoordinates; import com.main.sts.entities.DailyRunningBuses; import com.main.sts.entities.DailySubscriberData; import com.main.sts.service.BusesService; import com.main.sts.service.DailyRunningBusesService; import com.main.sts.service.DailySubscriberDataService; import com.main.sts.util.DateUtil; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/map") @PreAuthorize("isAuthenticated()") @Secured("ROLE_ADMIN") public class MapDataController { @Autowired private RolesUtility rolesUtility; @Autowired private DailyRunningBusesService dailyRunningBusesService; @Autowired private DailySubscriberDataService dailySubscriberDataService; @Autowired private BusesService busesService; @RequestMapping(value = "/getMapData", method = RequestMethod.POST) public @ResponseBody String mapData(HttpServletRequest request, ModelAndView model) { try { Date current_date = DateUtil.getTodayDateWithOnlyDate(); List<DailyRunningBuses> runningVehicles = dailyRunningBusesService.getDailyRunningBus(current_date, TripStatus.RUNNING); // //System.out.println(buses); if (runningVehicles.size() == 0) { return "none"; } else { String send = ""; for (DailyRunningBuses b : runningVehicles) { send = send + b.getUsers_in_bus() + ":" + b.getLatitude() + ":" + b.getLongitude() + ":" + b.getVehicle_status() + ":" + b.getVehicle_licence_number() + "+"; } // //System.out.println(send); return send; } } catch (Exception e) { e.printStackTrace(); return "none"; } } @RequestMapping(value = "/getSingleBusMapData", method = RequestMethod.POST) public @ResponseBody String getSingleBusMapData(HttpServletRequest request, ModelAndView model) { try { int bus_id = Integer.parseInt(request.getParameter("bus_id")); int trip_id = Integer.parseInt(request.getParameter("trip_id")); Date date = new Date(); Buses bus = busesService.getBusById(bus_id); String current_date_str = new SimpleDateFormat("yyyy-MM-dd").format(date); Date current_date = DateUtil.getTodayDateWithOnlyDate(); DailyRunningBuses buses = dailyRunningBusesService.getDailyRunningBusWithRunningStatus(current_date, trip_id); List<DailySubscriberData> dailySubscriberDatas = dailySubscriberDataService.getDailySubscribers(trip_id, current_date_str); DailyBusCoordinates busCoordinates = dailyRunningBusesService.getLatestBusCoordinates(current_date, trip_id); if (buses == null) { return "none"; } else { String send = ""; // System.out.println(buses); send = send + buses.getUsers_in_bus() + ":" + busCoordinates.getLatitude() + ":" + busCoordinates.getLongitude() + ":" + VehicleStatus.getVehicleStatus(buses.getVehicle_status()).getStatusText() + ":" + bus.getBus_licence_number() + "+"; return send; } } catch (Exception e) { e.printStackTrace(); return "none"; } } } <file_sep>package com.main.sts.dto; import java.io.Serializable; public class RouteDTO implements Serializable { // can be null for backward compatibility Integer commuter_id; String from_stop; String to_stop; Integer start_time_hour; Integer start_time_minutes; Integer end_time_hour; Integer end_time_minutes; public Integer getCommuter_id() { return commuter_id; } public void setCommuter_id(Integer commuter_id) { this.commuter_id = commuter_id; } public String getFrom_stop() { return from_stop; } public void setFrom_stop(String from_stop) { this.from_stop = from_stop; } public String getTo_stop() { return to_stop; } public void setTo_stop(String to_stop) { this.to_stop = to_stop; } public Integer getStart_time_hour() { return start_time_hour; } public void setStart_time_hour(Integer start_time_hour) { this.start_time_hour = start_time_hour; } public Integer getStart_time_minutes() { return start_time_minutes; } public void setStart_time_minutes(Integer start_time_minutes) { this.start_time_minutes = start_time_minutes; } public Integer getEnd_time_hour() { return end_time_hour; } public void setEnd_time_hour(Integer end_time_hour) { this.end_time_hour = end_time_hour; } public Integer getEnd_time_minutes() { return end_time_minutes; } public void setEnd_time_minutes(Integer end_time_minutes) { this.end_time_minutes = end_time_minutes; } } <file_sep>package com.main.sts.controllers; import javax.servlet.http.HttpServletRequest; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping(value = "/school_admin") @PreAuthorize("isAuthenticated()") @Secured("ROLE_ADMIN") public class LocationController { @RequestMapping(value = "/location_find", method = RequestMethod.GET) public ModelAndView location(ModelAndView model, HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/Location_find"); model.addObject("msg", "msg"); return model; } } <file_sep>package com.main.sts; import javax.annotation.Resource; import org.junit.Test; import com.main.sts.messageworkers.Mail; import com.main.sts.messageworkers.MailSender; public class MailSenderTest extends BaseTest { @Resource MailSender mailSender; @Test public void testSendEmail() { Mail email = new Mail("<EMAIL>", "test message", "Hello test message"); mailSender.sendMail(email); } } <file_sep>package com.main.sts.dto; public class EmailResponse { private int code; private boolean success; private String message; public EmailResponse(int code, String msg) { this.code = code; this.success = code == 200; this.message = msg; } public int getCode() { return this.code; } public boolean getStatus() { return this.success; } public String getMessage() { return this.message; } @Override public String toString() { return "EmailResponse [code=" + code + ", success=" + success + ", message=" + message + "]"; } }<file_sep>package com.main.sts.dao.sql; import java.util.List; import org.springframework.stereotype.Repository; import com.main.sts.entities.Session; @Repository public class SessionDao extends BaseDao { public void insert(Session session) { insertEntity(session); } public void update(Session session) { updateEntity(session); } public void delete(Session session) { deleteEntity(session); } public List<Session> getSessions() { return getAllRecords(Session.class); } } <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.PlexusMediatorDao; import com.main.sts.entities.PlexusMediatorRecord; @Service public class PlexusMediatorService { @Autowired private PlexusMediatorDao plexusdao; public void insertRecord(PlexusMediatorRecord mediatorRecord) { plexusdao.insert(mediatorRecord); } public List<PlexusMediatorRecord> getStudentByStudId(Integer id,String date) { return plexusdao.getStudents(id,date); } } <file_sep>package com.main.sts.controllers.webapp; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.http.HttpRequest; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.dto.RouteDTO; import com.main.sts.entities.Commuter; import com.main.sts.entities.SuggestRoute; import com.main.sts.service.RouteService; @Controller @RequestMapping("/webapp/route") public class RouteWebAppController extends CommonController{ private static final Logger logger = Logger.getLogger(RouteWebAppController.class); @Autowired private RouteService routeService; @RequestMapping(value = "/show_suggest_route") public ModelAndView suggestARoute(ModelAndView model, HttpServletRequest request) { try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/suggest_route"); return model; } @RequestMapping(value = "/suggest_route", method = RequestMethod.POST) public ModelAndView getSuggestedRoute(ModelAndView model, HttpSession session, HttpServletRequest request) { boolean status = false; try { // boolean loggedin = super.isLoggedIn(request); // if (!loggedin) { // model.setViewName("/login"); // return model; // } String from_stop = request.getParameter("from"); String to_stop = request.getParameter("to"); String start_time = request.getParameter("morning"); String[] sthour = start_time.split(":"); //sthour[0] is hour, sthour[1] is min AM or PM, String[] stmin = sthour[1].split(" "); // stmin[0] is min Integer start_time_hour = Integer.parseInt(sthour[0]); Integer start_time_minutes = Integer.parseInt(stmin[0]); String end_time = request.getParameter("evening"); String[] ehour = end_time.split(":"); //ehour[0] is hour, ehour[1] is min AM or PM, String[] emin = ehour[1].split(" "); // emin[0] is min Integer end_time_hour = Integer.parseInt(ehour[0]); Integer end_time_minutes = Integer.parseInt(emin[0]); session = super.getSession(request); Commuter commuter = super.getCommuter(request); int commuter_id = commuter.getCommuter_id(); SuggestRoute sr = new SuggestRoute(); sr.setFrom_stop(from_stop); sr.setTo_stop(to_stop); sr.setStart_time_hour(start_time_hour); sr.setStart_time_minutes(start_time_minutes); sr.setEnd_time_hour(end_time_hour); sr.setEnd_time_minutes(end_time_minutes); sr.setCommuter_id(commuter_id); status = routeService.suggestARoute(sr); } catch (Exception e) { e.printStackTrace(); } model.addObject("status", status); model.setViewName("/webapp/suggest_route"); return model; } } <file_sep>package com.main.sts.entities; import java.io.Serializable; public class PushMessage implements Serializable { String gcm_regid; String title; String message; public String getGcm_regid() { return gcm_regid; } public void setGcm_regid(String gcm_regid) { this.gcm_regid = gcm_regid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <file_sep>package com.main.sts.controllers.rest; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.main.sts.dto.Response; import com.main.sts.entities.Notification; import com.main.sts.service.NotificationService; import com.main.sts.service.ReturnCodes; @Controller @RequestMapping("/notifications") public class NotificationController { @Autowired private NotificationService notificationService; static final Logger logger = Logger.getLogger(NotificationController.class); @RequestMapping(value = "/findByCommuterId/{commuter_id}", method = RequestMethod.GET) public ResponseEntity<Response> sendNotification(@PathVariable int commuter_id) { List<Notification> notifications = null; try { notifications = notificationService.getNoticationByCommuterId(commuter_id); Response resp = new Response(); resp.response = notifications; resp.returnCode = ReturnCodes.SUCCESS.name(); // TODO: handle the response properly. return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); Response resp = new Response(); resp.response = notifications; resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>package com.main.sts.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.ParentDao; import com.main.sts.entities.Parents; @Service public class ParentService { @Autowired private ParentDao parentdao; public List<Parents> getEmails() { return parentdao.getParent(); } public String getEmailById(int subscriber_id) { return parentdao.getEmail(subscriber_id); } } <file_sep>package com.main.sts.controllers.rest; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.main.sts.dto.Response; import com.main.sts.dto.RouteStopsDTO; import com.main.sts.dto.StopsDTO; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.service.ReturnCodes; import com.main.sts.service.StopsService; @Controller @RequestMapping("/stops") public class StopsController { @Autowired private StopsService stopsService; static final Logger logger = Logger.getLogger(StopsController.class); @RequestMapping(value = "/list", method = RequestMethod.GET) public @ResponseBody List<Stops> getAllStops() { List<Stops> stops = null; try { stops = stopsService.getAllStops(); } catch (Exception e) { e.printStackTrace(); } return stops; } @RequestMapping(value = "/from_stops", method = RequestMethod.GET) public @ResponseBody List<StopsDTO> getFromStops() { Set<RouteStops> stops = null; boolean onlyPickupStops = true; try { stops = stopsService.getAllAvailableFromStops(); } catch (Exception e) { e.printStackTrace(); } // TODO: Add a check for empty List<StopsDTO> stopsDTOs = new ArrayList<StopsDTO>(); if (stops != null) { for (RouteStops rs : stops) { StopsDTO stop = stopsService.toStopsDTO(rs); stopsDTOs.add(stop); } } else { System.out.println("stops list is null"); } return stopsDTOs; } @RequestMapping(value = "/from_stops/{route_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> getRoutes(@PathVariable int route_id) { Response resp = new Response(); Set<RouteStops> routeStops = null; try { routeStops = stopsService.getAllAvailableFromStops(); // TODO: Add a check for empty List<StopsDTO> stopsDTOs = new ArrayList<StopsDTO>(); if (routeStops != null) { for (RouteStops rs : routeStops) { StopsDTO stop = stopsService.toStopsDTO(rs); stopsDTOs.add(stop); } resp.response = stopsDTOs; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } else { System.out.println("stops list is null"); resp.response = null; resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } catch (Exception e) { e.printStackTrace(); resp.response = null; resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } @RequestMapping(value = "/to_stops/{from_stop_id}", method = RequestMethod.GET) public @ResponseBody ResponseEntity<List<StopsDTO>> getToStops(@PathVariable int from_stop_id) { List<RouteStops> routeStopsList = null; try { routeStopsList = stopsService.getAllAvailableToStops(from_stop_id); } catch (Exception e) { e.printStackTrace(); } List<StopsDTO> stops = new ArrayList<StopsDTO>(); if (routeStopsList != null) { for (RouteStops rs : routeStopsList) { StopsDTO stop = stopsService.toStopsDTO(rs); stops.add(stop); } } return new ResponseEntity<List<StopsDTO>>(stops, HttpStatus.OK); } @RequestMapping(value = "/findRoutes", method = RequestMethod.GET) public @ResponseBody ResponseEntity<Response> getRoutes() { Response resp = new Response(); List<RouteStopsDTO> routeStops = null; try { routeStops = stopsService.getAllAvailableRoutesWithStops(); resp.response = routeStops; resp.returnCode = ReturnCodes.SUCCESS.name(); return new ResponseEntity<Response>(resp, HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); resp.response = null; resp.returnCode = ReturnCodes.UNKNOWN_ERROR.name(); return new ResponseEntity<Response>(resp, HttpStatus.SERVICE_UNAVAILABLE); } } } <file_sep>package com.main.sts.service; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.main.sts.dao.sql.DailySubscriberDataDao; import com.main.sts.entities.DailySubscriberData; @Service public class DailySubscriberDataService { private static final Logger logger = Logger.getLogger(DailySubscriberDataService.class); @Autowired private DailySubscriberDataDao dailySubscriberDataDao; @Autowired private BusesService busesService; @Autowired private TransportService transportService; @Autowired private TripService tripService; @Autowired private StopsService stopsService; @Autowired private DailyRunningBusesService dailyRunningBusesService; public List<DailySubscriberData> getDailySubscribers(int trip_id, String date) { return dailySubscriberDataDao.getDailySubscribersLeftOnBus(trip_id, date); } public List<DailySubscriberData> getDailyStudentSubscribers(int trip, String date) { return dailySubscriberDataDao.getDailySubscribers(trip, date, "student"); } public List<DailySubscriberData> getStudentByNameAndDate(String name, String date) { return dailySubscriberDataDao.getDailyStudents(name, date, "student"); } } <file_sep>package com.main.sts.controllers; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.main.sts.entities.RfidCards; import com.main.sts.service.RfidCardsService; import com.main.sts.util.RolesUtility; @Controller @RequestMapping(value = "/school_admin/rfid") @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_GUEST','ROLE_CUSTOMER_SUPPORT','ROLE_OPERATOR')") /* * @PreAuthorize("isAuthenticated()") * * @Secured("ROLE_ADMIN") */ public class StudentRfidController { private static final String type = "student"; private static final Logger logger = Logger.getLogger(StudentRfidController.class); @Autowired private RfidCardsService rfidCardsService; @Autowired private RolesUtility rolesUtility; @RequestMapping(value = "/student", method = RequestMethod.GET) public ModelAndView seniorHomePage(ModelAndView model, HttpServletRequest request) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); // System.out.println("inside student rifd controller"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/rfid/student_rfid_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("login_role", rolesUtility.getRole(request)); model.addObject("current_page", "student_rfid_list"); /* * List<RfidEntity> stuRfids = rfidDaoImpl.getRfidListByType(type); * Collections.sort(stuRfids); */ // //System.out.println(rfidDaoImpl.getRfidListByType("student")); /* * Sql database -- start */ List<RfidCards> cards = rfidCardsService.getRfidsByType(type); // System.out.println(cards); /* * Sql database -- end */ model.addObject("student_rfid_list", cards); return model; } @RequestMapping(value = "/student/add", method = RequestMethod.POST) public @ResponseBody String studentRfidAdd(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { // System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); /* * Sql database -- start */ boolean cardfound = rfidCardsService.rfidExists(rfid_number); if (cardfound == true) { return "rfid_exists"; } else { rfidCardsService.addRfid(rfid_number, type); logger.info("New Rfid number [ " + rfid_number + " ] has been registered with type Student"); return "rfid_inserted"; } /* * Sql database -- end */ /* * RfidEntity rfid = rfidDaoImpl.getRFIDByNumber(rfid_number); if (rfid * == null) { rfid = new RfidEntity(); // * //System.out.println("RFID "+rfid); rfid.setAllocated_time("none"); * rfid.setAllocated_to("none"); rfid.setAvailable("yes"); * rfid.setRfid_number(rfid_number); rfid.setType("student"); * rfid.setAllocated_person_name("none"); boolean reply = * rfidDaoImpl.saveRfid(rfid); * * if (reply == true) { logger.info("Student RFID " + rfid_number + * " added"); return "rfid_inserted"; } else { return * "rfid_notinserted"; } } else { return "rfid_exists"; } */ } @RequestMapping(value = "/student/update", method = RequestMethod.POST) public @ResponseBody String studentRfidUpdate(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String current_rfid = request.getParameter("current_rfid"); String new_rfid = request.getParameter("new_rfid"); // //System.out.println("Current rfid="+current_rfid+" new rfid="+new_rfid); boolean reply = rfidCardsService.updateRfid(current_rfid, new_rfid); if (reply == true) { logger.info("Rfid number [ " + current_rfid + " ] changed to [ " + new_rfid + " ] type Student"); return "rfid_inserted"; } else if (reply == false) { return "rfid_exists"; } else { return "rfid_notinserted"; } } @RequestMapping(value = "/student/delete", method = RequestMethod.POST) public @ResponseBody String studentRfidDelete(HttpServletRequest request) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); boolean reply = rfidCardsService.deleteRfid(rfid_number); if (reply == true) { logger.info("Rfid number [ " + rfid_number + " ] type Student has been deleted"); return "rfid_deleted"; } else { return "rfid_notdeleted"; } } // search RFID starts @RequestMapping(value = "/student/search", method = RequestMethod.POST) public @ResponseBody String searchRfid(HttpServletRequest request, Model model, HttpSession session) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { return "redirect:/j_spring_security_logout"; } String rfid_number = request.getParameter("rfid_number"); List<RfidCards> rfids = rfidCardsService.searchRfids(rfid_number, "student"); session.setAttribute("rfids", rfids); // logger.info(rfids); return "/sts/school_admin/rfid/studentSearch"; } @RequestMapping(value = "/studentSearch", method = RequestMethod.GET) public ModelAndView studentSearchResponse(ModelAndView model, HttpServletRequest request, HttpSession session) { // Authentication auth = // SecurityContextHolder.getContext().getAuthentication(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { model.setViewName("redirect:/j_spring_security_logout"); return model; } model.setViewName("/school_admin/rfid/student_rfid_list"); DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); model.addObject("date", formatter.format(new Date())); model.addObject("login_name", auth.getName()); model.addObject("current_page", "student_rfid_list"); List<RfidCards> rfids = (List<RfidCards>) session.getAttribute("rfids"); model.addObject("student_rfid_list", rfids); // //System.out.println(rfids); if (rfids.isEmpty()) { // //System.out.println("null"); model.addObject("student_rfid_list", rfidCardsService.getRfidsByType(type)); model.addObject("error_message", "noMatching"); } return model; } // search RFID ends @RequestMapping(value = "/removeAllRFIDSByTripIds", method = RequestMethod.POST) public @ResponseBody String removeAllTripsByTripIds(ModelAndView model, HttpServletRequest request) { // System.out.println("inside delete rfids method"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) == false) { System.out.println("inside if"); return "redirect:/j_spring_security_logout"; } String rfids = request.getParameter("rfids"); // //System.out.println(rfids); String rfidsArray[] = rfids.split(","); int totalItems = rfidsArray.length; // //System.out.println(totalItems); for (int i = 1; i <= totalItems; i++) { rfidCardsService.deleteRfid(rfidsArray[i - 1]); RfidCards rfidCard = rfidCardsService.getRfidCard(rfidsArray[i - 1]); rfidCardsService.deleteRfid(rfidCard); logger.info("Rfid [ " + rfidCard.getRfid_number() + " ] deleted from [ " + rfidCard.getType() + " ] cards list"); } // return null; return "student"; } } <file_sep>package com.ec.eventserver.service; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.ec.eventserver.dto.request.VehicleGpsDataRequest; import com.ec.eventserver.models.DailyBusStops; import com.ec.eventserver.models.EtaProcess; import com.main.sts.entities.DailyRunningBuses; import com.main.sts.entities.RouteStops; import com.main.sts.entities.Stops; import com.main.sts.entities.Trips; import com.main.sts.service.DailyRunningBusesService; import com.main.sts.service.DashBoardSettingsService; import com.main.sts.service.RouteStopsService; import com.main.sts.service.StopsService; import com.main.sts.service.TripService; import com.main.sts.util.SystemConstants; @Component public class EtaProcessor { @Autowired private DailyRunningBusesService dailyRunningBusesService; @Autowired private TripService tripService; @Autowired private StopsService stopservice; @Autowired private EtaFinder etaFinder; @Autowired private SystemProperties systemProperties; @Autowired private DashBoardSettingsService dashBoardSettingsService; // @Autowired // private SendMail sendmail; // @Autowired // private SendSms sendsms; @Autowired private RouteStopsService routeStopsService; @Autowired private DailyBusStopService dailyBusStops; @Autowired private EtaProcessService etaservice; private static final Logger logger = Logger.getLogger(EtaProcess.class); public void procesEta(VehicleGpsDataRequest data, Trips trip, DailyRunningBuses dailyRunningBuses) { // logger.info("Eta Process Starts...."); String expected_time = ""; int eta_time = systemProperties.getEta_send_time(); // DashboardSettings admin = // dashBoardSettingsService.getDashBoardSettings(); int current_stop_number = 0; int check_eta_time = 0; // DailyBusStops current_stop = null; RouteStops route_stop = null; String msg = ""; // int i=0; try { List<RouteStops> all_stops_inroute = routeStopsService.getAllRouteStops(trip.getTripDetail().getRouteid()); // logger.info("all stops " + all_stops_inroute); List<DailyBusStops> daily_stop = dailyBusStops.getAllDailyBusStops(trip.getId(), data.getCreated_at()); // logger.info("daily stops "+daily_stop); List<EtaProcess> count_value = etaservice.getEtaByTripIdAndDate(trip.getId(), data.getCreated_at()); if (daily_stop.size() == 0 && count_value.size() == 0) { // System.out.println("trip id is "+trip.getRouteid()); route_stop = routeStopsService.getRouteStopByRouteIdAndStopNo(trip.getTripDetail().getRouteid(), 1); // logger.info(" first stop "+route_stop); check_eta_time = etaservice.getEtaCheckTime(data, route_stop, trip); } else { // System.out.println("else part"); DailyBusStops last_stop = dailyBusStops.getLastStopsByTripAndDate(data.getCreated_at(), trip.getId()); // System.out.println("last stop "+last_stop); if (last_stop == null) { /* * EtaProcess et=etaservice.getlastEta(trip.getId(), * data.getDate()); System.out.println("eta stop "+et); */ current_stop_number = 0; } else { int cs = etaservice.getStopNumber(trip.getTripDetail().getRouteid(), last_stop.getRoutestop_id()); // RouteStops cs = // routeStopsService.getRouteStopNumber(trip.getRouteid(), // last_stop.getRoutestop_id()); // /System.out.println("i value "+cs); if (cs > current_stop_number) current_stop_number = cs; } // System.out.println("current stop " + current_stop_number); } for (RouteStops routeStopscheck : all_stops_inroute) { int eta_diff = etaservice.getTimeForEtaBelowfiveMin(data, routeStopscheck, trip); if (routeStopscheck.getStop_number() > current_stop_number && eta_diff <= 5) { check_eta_time = etaservice.getEtaCheckTime(data, routeStopscheck, trip); route_stop = routeStopscheck; // if (check_eta_time == eta_time) // { // logger.info("break the loop"); // break; // logger.info("check etatime "+check_eta_time+" eta time "+eta_time); if ((check_eta_time <= eta_time && check_eta_time > 0) || (check_eta_time <= 0)) { //dd int avg_speed = etaservice.getAvgSpeed(trip.getId(), data.getCreated_at(), etaFinder); System.out.println("the avg speed is " + avg_speed +" meter/min"); if (avg_speed == 0) avg_speed = (int) data.getVehicle_speed(); Stops stop = stopservice.getStop(route_stop.getStop_id()); double eta = etaFinder.getEta(data.getGps_lat(), data.getGps_long(), Double.parseDouble(stop.getLatitude()), Double.parseDouble(stop.getLongitude()), avg_speed); System.out.println("the eta to bus stop " + stop.getStop_name() + " is " + eta); int late_time = etaservice.calculateTimeDifferenceUsingTimeStamp(data.getTime(), route_stop.getStop_time()); System.out.println("late time " + late_time); if ((late_time > SystemConstants.ETA_LATE_TIME) || late_time < 0) { String etaTime = etaservice.calculateExpectedTime(route_stop.getStop_time(), late_time); /* * if (eta == 0){ expected_time = "NA"; * msg=SystemConstants.ETA_MSG; } * * else { */ expected_time = etaTime; msg = "Bus " + data.getVehicle_id() + " will be late at stop " + route_stop.getStop().getStop_name() + " and expected time to reach is " + expected_time; System.out.println("msg:"+msg); // } if (eta > 0) { EtaProcess etadata = etaservice.getEtaStopCount(data.getCreated_at(), route_stop.getStop_id(), trip.getId(), trip.getTripDetail().getBusid()); if (etadata == null) { // sendmail here // sendmail.sendMail(trip.getId(),msg,routeStopscheck.getStop_id()); // sendmail.sendSms(trip.getId(), msg, // routeStopscheck.getStop_id()); etaservice.insertEtaProcess(data, trip, route_stop, expected_time, 0); logger.info("Eta Inserted"); } else { if (!(expected_time.equals(etadata.getExpected_time()))) { // sendEmailAndSms(routeStopsEntity, // data, sendMail, // sendSms, // expected_time,tripEntity.getId()); // sendmail.sendMail(trip.getId(),msg,routeStopscheck.getStop_id()); etaservice.updateEtaProcess(data, trip, route_stop, expected_time, etadata.getCount(), etadata.getId()); // sendmail.sendSms(trip.getId(), msg, // routeStopscheck.getStop_id()); logger.info("Eta Updated " + etadata.getStop_name() + " with expected time " + expected_time); } } } } else { logger.info("Bus " + data.getVehicle_id() + " is on Time....So ETA has not been Sent"); } } // } } } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package com.main.sts.controllers.webapp; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.main.sts.common.CommonConstants.TransactionStatus; import com.main.sts.common.CommonConstants.TransactionType; import com.main.sts.dto.AccountDTO; import com.main.sts.dto.RechargeRequest; import com.main.sts.dto.Response; import com.main.sts.dto.response.PaymentTransactionDTO; import com.main.sts.dto.response.TransactionResponse; import com.main.sts.entities.Commuter; import com.main.sts.entities.PaymentTransaction; import com.main.sts.entities.RechargeOptions; import com.main.sts.entities.TransactionInfo; import com.main.sts.service.PaymentTransactionService; import com.main.sts.service.RechargeOptionsService; import com.main.sts.service.ReturnCodes; import com.main.sts.service.TransactionService; import com.main.sts.util.SystemConstants; @Controller @RequestMapping("/webapp/transaction") public class TransactionWebAppController extends CommonController{ @Autowired private TransactionService txService; @Autowired private PaymentTransactionService paymentTxService; @Autowired private RechargeOptionsService rechargeOptionsService; static final Logger logger = Logger.getLogger(TransactionWebAppController.class); @RequestMapping(value = "/my_transactions", method = RequestMethod.GET) public ModelAndView findByCommuterId(ModelAndView model, HttpServletRequest request, HttpSession session) { session = super.getSession(request); Commuter commuter = super.getCommuter(request); int commuter_id = commuter.getCommuter_id(); List<TransactionInfo> txs = null; try { Integer offset = (request.getParameter("offset") != null && !request.getParameter("offset").trim().isEmpty()) ? Integer.parseInt(request.getParameter("offset")) : 0; Integer limit = (request.getParameter("limit") != null && !request.getParameter("limit").trim().isEmpty()) ? Integer.parseInt(request.getParameter("limit")) : 50; txs = txService.getTransactionsByCommuterId(commuter_id, offset, limit); model.addObject("transactionsList", txs); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/my_transactions"); model.addObject("current_page", "my_transactions"); return model; } @RequestMapping(value = "/my_wallet", method = RequestMethod.GET) public ModelAndView getMyWallet(ModelAndView model, HttpSession session, HttpServletRequest request) { try { model = getAccountBalance(model, session, request); model = getRechargeOptions(model); } catch (Exception e) { e.printStackTrace(); } model.setViewName("/webapp/my_wallet"); return model; } @RequestMapping(value = "/account/balance", method = RequestMethod.GET) public ModelAndView getAccountBalance(ModelAndView model, HttpSession session, HttpServletRequest request) { AccountDTO acc = new AccountDTO(); request.getSession(false); try { acc = txService.getUserAccountBalance(((Commuter)session.getAttribute("commuter")).getCommuter_id()); acc.setReturnCode(ReturnCodes.SUCCESS); } catch (Exception e) { e.printStackTrace(); acc.setReturnCode(ReturnCodes.UNKNOWN_ERROR); } model.addObject("acc", acc); return model; } @RequestMapping(value = "/get_recharge_options") public ModelAndView getRechargeOptions(ModelAndView model) { Response resp = new Response(); try { List<RechargeOptions> list = rechargeOptionsService.getRechargeOptions(true); if (list != null) { resp.setReturnCode(ReturnCodes.SUCCESS.name()); model.addObject("list", list); model.addObject("resp",resp); } else { resp.setReturnCode(ReturnCodes.UNKNOWN_ERROR.name()); model.addObject("resp", resp); } return model; } catch (Exception e) { e.printStackTrace(); resp.response = null; resp.setReturnCode(ReturnCodes.UNKNOWN_ERROR.name()); model.addObject("resp", resp); return model; } } // String merchant_key="MtLdu1"; // String salt="VD2Kc8Px"; // String action1 =""; // String base_url="https://test.payu.in"; String merchant_key="Vh10ae"; String salt="U3XzuivH"; String action1 =""; String base_url="https://secure.payu.in"; @RequestMapping(value = "/payUMoney", method = RequestMethod.POST) public ModelAndView showPayUMoneyPage(ModelAndView model, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes, HttpSession session) { try{ session = super.getSession(request); Commuter commuter = super.getCommuter(request); int commuter_id = commuter.getCommuter_id(); String txnid = ""; String recharge_options_id = request.getParameter("recharge_options_id"); String amount = request.getParameter("amount_selected"); String firstname = commuter.getName(); String email = commuter.getEmail(); String phone = commuter.getMobile(); String productinfo = "ECRecharge"; String surl = "https://payu.herokuapp.com/success"; String furl = "https://payu.herokuapp.com/failure"; //String url = request.getScheme() + "://"+ request.getServerName(); String url = "https" + "://"+ request.getServerName(); System.out.println("url:"+url); String contextPath = request.getContextPath(); System.out.println("contextPath:"+contextPath); if (contextPath != null && !contextPath.equals("")) { if (!url.endsWith("/")) { url = url + "/"; } // contextPath:/webapp if (contextPath.startsWith("/")) { contextPath = contextPath.substring(1); } url = url + contextPath; } // surl="https://dev.easycommute.co/webapp/webapp/transaction/payUMoney/success"; // furl="https://dev.easycommute.co/webapp/webapp/transaction/payUMoney/failure"; if (!url.endsWith("/")) { url = url + "/"; } surl = url + "webapp/transaction/payUMoney/success"; furl = url + "webapp/transaction/payUMoney/failure"; System.out.println("surl:"+surl); System.out.println("furl:"+furl); String service_provider = "payu_paisa"; System.out.println("recharge_options_id:"+recharge_options_id); Random rand = new Random(); String rndm = Integer.toString(rand.nextInt())+(System.currentTimeMillis() / 1000L); txnid=hashCal("SHA-256",rndm).substring(0,20); Map<String,String> params= new HashMap<String,String>(); params.put("key", merchant_key); params.put("txnid", txnid); params.put("amount", amount); params.put("firstname", firstname); params.put("email", email); params.put("phone", phone); params.put("productinfo", productinfo); params.put("surl", surl); params.put("furl", furl); params.put("service_provider", service_provider); params.put("udf1", recharge_options_id); params.put("udf2", txnid); params.put("udf3", "" + commuter_id); String hash = createHash(params, salt); System.out.println("hash:"+hash); params.put("hash", hash); //redirectAttributes.addFlashAttribute("message", "User " + login + " deleted"); // String action = test(params); // //return "redirect:/webapp/payuform"; // for (String s : params.keySet()) { // redirectAttributes.addFlashAttribute(s, params.get(s)); // redirectAttributes.addAttribute(s, params.get(s)); // } model.addObject("params", params); model.setViewName("/webapp/payuform"); //System.out.println("action:"+action + "-- params:"+params); //return "redirect:"+action; //request.getParameterMap().putAll(params); } catch (Exception e) { e.printStackTrace(); } return model; } public String createHash(Map<String, String> params, String salt) { String hashString = ""; String hash = ""; String hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10"; String[] hashVarSeq = hashSequence.split("\\|"); for (String part : hashVarSeq) { hashString = (empty(params.get(part))) ? hashString.concat("") : hashString.concat(params.get(part)); hashString = hashString.concat("|"); } hashString = hashString.concat(salt); hash = hashCal("SHA-512", hashString); return hash; } public String hashCal(String type, String str) { byte[] hashseq = str.getBytes(); StringBuffer hexString = new StringBuffer(); try { MessageDigest algorithm = MessageDigest.getInstance(type); algorithm.reset(); algorithm.update(hashseq); byte messageDigest[] = algorithm.digest(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) hexString.append("0"); hexString.append(hex); } } catch (NoSuchAlgorithmException nsae) { } return hexString.toString(); } public boolean empty(String s) { if (s == null || s.trim().equals("")) return true; else return false; } @RequestMapping(value = "/payUMoney/success", method = RequestMethod.POST) public String handleSuccessTransaction(ModelAndView model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { System.out.println("-------------Payumoney success transaction---------------"); return handleTransaction(model, request, response, session); } @RequestMapping(value = "/payUMoney/failure", method = RequestMethod.POST) public String handleFailedTransaction(ModelAndView model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { System.out.println("-------------Payumoney failed transaction---------------"); //return handleTransaction(model, request, response, session); return "redirect:/webapp/transaction/my_wallet"; } public String handleTransaction(ModelAndView model, HttpServletRequest request, HttpServletResponse response, HttpSession session) { String status = request.getParameter("status"); String firstname = request.getParameter("firstname"); String amount = request.getParameter("amount"); String txnid = request.getParameter("txnid"); String posted_hash = request.getParameter("hash"); String key = request.getParameter("key"); String productinfo = request.getParameter("productinfo"); String email = request.getParameter("email"); String recharge_options_id = request.getParameter("udf1"); String commuter_id_str = request.getParameter("udf3"); Enumeration paramNames = request.getParameterNames(); Map<String, String> params = new HashMap<String, String>(); while (paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); String paramValue = request.getParameter(paramName); params.put(paramName, paramValue); } //String retHashSeq = "salt|status|udf10|udf9|udf8|udf7|udf6|udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key"; String retHashSeq = "status|udf10|udf9|udf8|udf7|udf6|udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key"; String[] hashVarSeq = retHashSeq.split("\\|"); retHashSeq=salt+'|'; for (String part : hashVarSeq) { retHashSeq = (empty(params.get(part))) ? retHashSeq.concat("") : retHashSeq.concat(params.get(part)); retHashSeq = retHashSeq.concat("|"); } System.out.println("retHashSeq:"+retHashSeq); //String hash = hashCal("SHA-512", retHashSeq); retHashSeq = retHashSeq.substring(0,retHashSeq.length()-1);//due to extra pipe (|) String hash = hashCal("SHA-512", retHashSeq); try { System.out.println(hash + "------------------------" + posted_hash); if (!hash.equals(posted_hash)) { response.getWriter().print(hash + "<br/>"); response.getWriter().print(posted_hash + "<br/>"); response.getWriter().print("Invalid Transaction. Please try again"); } else { Commuter c = ((Commuter) session.getAttribute("commuter")); // giving preference to the sessions's commuter_id; int commuter_id = -1; if (c != null) { commuter_id = c.getCommuter_id(); } else { commuter_id = Integer.parseInt(commuter_id_str); } PaymentTransaction tx = populatePaymentTxFields(params, commuter_id); Integer txId = paymentTxService.insertUserPaymentDetails(tx); if (txId != -1) { Integer rId = Integer.parseInt(recharge_options_id); RechargeOptions rechargeOptions = rechargeOptionsService.getRechargeOptions(rId); RechargeRequest rechargeReq = new RechargeRequest(); rechargeReq.setCommuter_id(commuter_id); rechargeReq.setPoints(rechargeOptions.getNum_credits_offered()); rechargeReq.setTx_type(TransactionType.CREDIT.intValue()); rechargeReq.setAdmin_id_or_name(null); rechargeReq.setPayment_tx_id(txId); if (status.equals("success")) { rechargeReq.setTx_status(TransactionStatus.SUCCESS.intValue()); TransactionResponse txResp = txService.userRechargeSuccessfulTransaction(rechargeReq); System.out.println("Inserted a successful recharge for commuter_id:" + commuter_id + " for amount:" + amount); } else { rechargeReq.setTx_status(TransactionStatus.FAILED.intValue()); TransactionResponse txResp = txService.userRechargeFailedTransaction(rechargeReq); System.out.println("Inserted a failed recharge for commuter_id:" + commuter_id + " for amount:" + amount); } } response.getWriter().print("<h3>Thank You. Your order status is " + status + "</h3>"); response.getWriter().print("<h4>Your Transaction ID for this transaction is " + txnid + "</h4>"); response.getWriter().print( "<h4>We have received a payment of Rs. " + amount + "Your order will soon be shipped.</h4>"); } } catch (Exception e) { e.printStackTrace(); } //return "redirect:/my_wallet"; return "redirect:/webapp/transaction/my_wallet"; } public PaymentTransaction populatePaymentTxFields(Map<String, String> params, int commuer_id) { PaymentTransaction tx = new PaymentTransaction(); tx.commuter_id = commuer_id; tx.mihpayid = params.get("mihpayid"); tx.mode = params.get("mode"); tx.txnid = params.get("txnid"); tx.amount = Double.parseDouble(params.get("amount")); tx.email = params.get("email"); tx.mobile = params.get("phone"); tx.status = params.get("status"); tx.bank_ref_num = params.get("bank_ref_num"); tx.bankcode = params.get("bankcode"); tx.error = params.get("error"); tx.error_message = params.get("error_Message"); tx.discount = Double.parseDouble(params.get("discount")); tx.net_amount_debit = (Double.valueOf((Double.parseDouble(params.get("net_amount_debit"))))).intValue(); tx.created_at = new Date(); return tx; } public String test(Map<String,String> params){ /* String merchant_key="Vh10ae"; String salt="U3XzuivH"; String action1 =""; String base_url="https://secure.payu.in"; */ int error=0; String hashString=""; // Enumeration paramNames = request.getParameterNames(); // Map<String,String> params= new HashMap<String,String>(); // while(paramNames.hasMoreElements()) // { // String paramName = (String)paramNames.nextElement(); // // String paramValue = request.getParameter(paramName); // // params.put(paramName,paramValue); // } //Map<String,String> params= (HashMap<String,String>)request.getAttribute("params"); String txnid =""; if(empty(params.get("txnid"))){ Random rand = new Random(); String rndm = Integer.toString(rand.nextInt())+(System.currentTimeMillis() / 1000L); txnid=hashCal("SHA-256",rndm).substring(0,20); params.put("txnid", txnid); } else txnid=params.get("txnid"); String udf2 = txnid; String txn="abcd"; String hash=""; String hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10"; if(empty(params.get("hash")) && params.size()>0) { if( empty(params.get("key")) || empty(params.get("txnid")) || empty(params.get("amount")) || empty(params.get("firstname")) || empty(params.get("email")) || empty(params.get("phone")) || empty(params.get("productinfo")) || empty(params.get("surl")) || empty(params.get("furl")) || empty(params.get("service_provider")) ) error=1; else{ String[] hashVarSeq=hashSequence.split("\\|"); for(String part : hashVarSeq) { hashString= (empty(params.get(part)))?hashString.concat(""):hashString.concat(params.get(part)); hashString=hashString.concat("|"); } hashString=hashString.concat(salt); hash=hashCal("SHA-512",hashString); action1=base_url.concat("/_payment"); } } else if(!empty(params.get("hash"))) { hash=params.get("hash"); action1=base_url.concat("/_payment"); } params.put("hash", hash); params.put("udf2", txnid); return action1; } } <file_sep>package com.main.sts; import java.util.List; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.entities.BusFarePriceEntity; import com.main.sts.entities.Stops; import com.main.sts.service.FareService; import com.main.sts.service.GoogleMapService; import com.main.sts.service.GoogleMapService.DistanceAndTimeDuration; import com.main.sts.service.RouteStopsService; import com.main.sts.service.StopsService; import com.main.sts.service.VehicleTrackingService.DistanceMatrix; public class FareServiceTest extends BaseTest { @Resource RouteStopsService routeStopService; @Resource private FareService fareService; @Resource private StopsService stopsService; @Resource private GoogleMapService googleMapService; @Test public void testFindAll() { Assert.assertFalse(fareService.findAll().isEmpty()); for (BusFarePriceEntity c : fareService.findAll()) { System.out.println(c.getSource_stop_id() + "--" + c.getDest_stop_id()); System.out.println(c.getSource_stop().getStop_name() + "--" + c.getDest_stop().getStop_name()); } } @Test public void findAllStops() { List<Stops> stops = routeStopService.getAllStops(); for (Stops stop : stops) { for (Stops stop1 : stops) { if (stop.getId() == stop1.getId()) { continue; } BusFarePriceEntity entity = fareService.fetchFare(stop.getId(), stop1.getId()); if (entity == null) { System.out.println("can't find " + stop.getStop_name() + "---" + stop1.getStop_name()); } } } } @Test public void findAllStopsThatFall() { List<Stops> stops = stopsService.getAllStops(); for (Stops stop : stops) { for (Stops stop1 : stops) { if (stop.getId() == stop1.getId()) { continue; } BusFarePriceEntity entity = fareService.fetchFare(stop.getId(), stop1.getId()); if (entity == null) { System.out.println("can't find " + stop.getStop_name() + "---" + stop1.getStop_name()); } } } } @Test public void fetchFare() { int source_stop_id = 33; int dest_stop_id = 89; BusFarePriceEntity entity = fareService.fetchFare(source_stop_id, dest_stop_id); System.out.println(entity); } @Test public void uploadAllDistanceAndTimeDuration() { Assert.assertFalse(fareService.findAll().isEmpty()); for (BusFarePriceEntity c : fareService.findAll()) { System.out.println(c.getSource_stop_id() + "--" + c.getDest_stop_id()); System.out.println(c.getSource_stop().getStop_name() + "--" + c.getDest_stop().getStop_name()); if (!c.getDistance().startsWith("km")) { continue; } Stops sourceStop = c.getSource_stop(); Stops destStop = c.getDest_stop(); DistanceMatrix dm = new DistanceMatrix(); dm.vehicle_lat = sourceStop.getLatitude().trim(); dm.vehicle_long = sourceStop.getLongitude().trim(); dm.booking_stop_lat = destStop.getLatitude().trim(); dm.booking_stop_long = destStop.getLongitude().trim(); DistanceAndTimeDuration dtd = googleMapService.getDistanceAndTimeDuration(dm); c.setDistance(dtd.distance); c.setTime_duration(dtd.time_duration); System.out.println(c.getSource_stop().getStop_name()+"--"+c.getDest_stop().getStop_name()+"--"+dtd.distance+"---"+dtd.time_duration); fareService.updateFare(c); } } } <file_sep>package com.main.sts.dao.sql; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Repository; import com.main.sts.entities.Alerts; @Repository public class AlertsDao extends BaseDao { public void insertAlerts(Alerts address) { insertEntity(address); } public void updateAlerts(Alerts address) { updateEntity(address); } public Alerts getAlerts(int subscriber_id, String subscriber_type, String alert_type) { String query = "from Alerts b where b.subscriber_id=? and b.subscriber_type=? and b.alert_type=?"; Map<Integer, Object> parameters = new HashMap<Integer, Object>(); parameters.put(0, subscriber_id); parameters.put(1, subscriber_type); parameters.put(2, alert_type); return getSingleRecord(Alerts.class, query, parameters); } } <file_sep>package com.main.sts; import java.util.List; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.dto.BookingDTO; import com.main.sts.dto.response.BookingCancellationResponse; import com.main.sts.dto.response.BookingResponse; import com.main.sts.dto.response.CommuterBookingResponse; import com.main.sts.dto.response.CommuterResponse; import com.main.sts.dto.response.PreBookingDetails; import com.main.sts.dto.response.StopsResponseDTO; import com.main.sts.entities.Booking; import com.main.sts.entities.BookingWebDTO; import com.main.sts.service.BookingService; import com.main.sts.service.SOSService; public class SOSServiceTest extends BaseTest { @Resource private SOSService sosService; @Test public void testRaiseSOSAlert() { int commuter_id = 91; commuter_id = 163; boolean sendEnabled = false; sosService.raiseAlertForSOSHelp(commuter_id, sendEnabled); } } <file_sep>package com.main.sts.service; import java.util.List; import javax.annotation.Resource; import junit.framework.Assert; import org.junit.Test; import com.main.sts.BaseTest; import com.main.sts.entities.RechargeOptions; public class RechargeOptionsServiceTest extends BaseTest { @Resource private RechargeOptionsService rechargeOptionsService; @Test public void getAllRechageOptions() { List<RechargeOptions> rechargeOptions = rechargeOptionsService.getRechargeOptions(true); for (RechargeOptions r : rechargeOptions) { System.out.println(r.getRecharge_amount() + "--" + r.getNum_credits_offered()); } } @Test public void insertARechargeOption() { RechargeOptions r = new RechargeOptions(); r.setEnabled(true); r.setRecharge_amount(20); r.setNum_credits_offered(20); Integer id = rechargeOptionsService.insertARechargeOption(r); System.out.println(id); Assert.assertNotNull(id);; Assert.assertNotSame(-1, id);; } @Test public void updateARechargeOption() { boolean enabled = true; int recharge_amount = 12; int num_credits_offered = 5; int recharge_option_id = 7; boolean status = rechargeOptionsService.updateRechargeOptions(recharge_option_id, recharge_amount, num_credits_offered, enabled); System.out.println(status); RechargeOptions ro = rechargeOptionsService.getRechargeOptions(recharge_option_id); System.out.println(ro.getRecharge_amount()); Assert.assertEquals(ro.getRecharge_amount(), recharge_amount); } }
c96efbbd424f7d534b0dbf85a1cdf5fd6f77704a
[ "JavaScript", "Java", "INI" ]
153
Java
manishsharma11/webapp
e9e2946081969a0e8d7fe4d318acaea4c91b321c
9f539c1a9a6b89bf2f2fcfa2f0a7b625668a8268
refs/heads/master
<repo_name>DDoS000/Love-s-University<file_sep>/demo/nakornfood-master/flask_app.py from flask import Flask, render_template, flash, redirect, url_for, session, request, logging import firebase_admin from firebase_admin import credentials from firebase_admin import firestore from functools import wraps import pyrebase app = Flask(__name__) configuse = { "type": "service_account", "project_id": "foodmanage-e63a1", "private_key_id": "bda07ba57843d1e3fa3219f8549607b357a24c02", "private_key": "-----<KEY>", "client_email": "<EMAIL>", "client_id": "103611357675025426296", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-jvifj%40foodmanage-e63a1.iam.gserviceaccount.com" } # Use a service account cred = credentials.Certificate(configuse) firebase_admin.initialize_app(cred) db = firestore.client() fbConfig = { "apiKey": "<KEY>", "authDomain": "foodmanage-e63a1.firebaseapp.com", "databaseURL": "https://foodmanage-e63a1.firebaseio.com", "projectId": "foodmanage-e63a1", "storageBucket": "foodmanage-e63a1.appspot.com", "messagingSenderId": "1024309103110", "appId": "1:1024309103110:web:5895822a1b04b8a9ffd187" } app.secret_key = '802a10465059f4276f654ab46b8033a2' firebase = pyrebase.initialize_app(fbConfig) auth = firebase.auth() database = firebase.database() def GetDataUser(uid): doc_ref = db.collection(u'users').document(uid) doc = doc_ref.get() docs = doc.to_dict() return docs # Check if user logged in def is_logged_in(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: return redirect(url_for('login')) return wrap @app.route('/') def index(): if 'logged_in' in session: return redirect(url_for('dashboard')) return render_template('login.html') # Dashboard @app.route('/dashboard') @is_logged_in def dashboard(): return render_template('dashboard.html') @app.route('/login', methods=['GET', 'POST']) def login(): if 'logged_in' in session: return redirect(url_for('dashboard')) if request.method == 'POST': email = request.form['email'] password = request.form['password'] try: user = auth.sign_in_with_email_and_password(email, password) # Passed docs = GetDataUser(user["localId"]) print(docs) print(docs["acc"]["manage"]) if docs["acc"]["manage"] == True: session['logged_in'] = True session['uid'] = user["localId"] session['email'] = user["email"] session['storename'] = docs["store"]["storename"] flash('เข้าสู้ระบบสําเร็จ', 'success') return redirect(url_for('dashboard')) else: flash('คุณไม่มีสิทธิ์เข้าถึง', 'success') return redirect(url_for('dashboard')) except Exception as Error: print(Error) error = 'อีเมลล์หรือรหัสผ่านไม่ถูกต้อง' return render_template('login.html', error=error) return render_template('login.html') @app.route('/manageStore/', methods=['GET', 'POST']) @is_logged_in def manageStore(): docs = GetDataUser(session['uid']) try: session['storename'] = docs["store"]["storename"] storename = docs["store"]["storename"] desc = docs["store"]["desc"] Open = docs["store"]["time"]["open"] close = docs["store"]["time"]["close"] lat = docs["store"]["location"]["lat"] lng = docs["store"]["location"]["lng"] except Exception: print(u'No such document!') storename = "" desc = "" Open = "" close = "" lat = 0 lng = 0 if request.method == "POST": storename = request.form['storename'] desc = request.form['desc'] Open = request.form['open'] close = request.form['close'] lat = request.form['lat'] lng = request.form['lng'] data = { u"store": { u"storename": str(storename), u"desc": str(desc), u"time": { u"open": str(Open), u"close": str(close) }, u"location": { u"lat": float(lat), u"lng": float(lng) } } } session['storename'] = storename try: db.collection(u'users').document(session['uid']).update(data) flash('อัพเดทข้อมูลสําเร็จ', 'success') return render_template('manageStore.html', storename=storename, desc=desc, Open=Open, close=close, lat=lat, lng=lng) except KeyError: print(KeyError) return render_template('manageStore.html', storename=storename, desc=desc, Open=Open, close=close, lat=lat, lng=lng) return render_template('manageStore.html', storename=storename, desc=desc, Open=Open, close=close, lat=lat, lng=lng) @app.route('/manageFood/', methods=['GET', 'POST']) @is_logged_in def manageFood(): docs = GetDataUser(session['uid']) try: foods = docs["menu"] print("getfoodspass") except KeyError: print("getfoodsError") foods = [{'photourl': '', 'name': 'ยังไม่มีข้อมูลในระบบ', 'detail': 'ยังไม่มีข้อมูลในระบบ', 'price': 'ยังไม่มีข้อมูลในระบบ', 'foodId': 'notvalue'}] return render_template('manageFood.html', foods=foods) @app.route('/addfoods/', methods=['GET', 'POST']) @is_logged_in def addfoods(): if request.method == "POST": foodname = request.form['foodname'] detail = request.form['foodedtail'] price = request.form['foodprice'] url = request.form['url'] print("setdata") try: counts = GetDataUser(session['uid'])['count'] counts += 1 except KeyError: try: print("UP0") counts = 0 db.collection(u'users').document( session['uid']).update({u"count": 0}) except KeyError: print("upcountna") print("Error Get data count") print(counts) data = { u"foodId": counts, u"name": foodname, u"detail": detail, u"price": price, u"photourl": url } try: db.collection(u'users').document( session['uid']).update({u"count": counts}) print("upcountpass") db.collection(u'users').document(session['uid']).update( {u'menu': firestore.ArrayUnion([data])}) except KeyError: print(KeyError) return redirect(url_for('manageFood')) @app.route('/manageSeat') @is_logged_in def manageSeat(): return render_template('manageSeat.html') @app.route('/ar') def ar(): return render_template('ar.html') @app.route('/ar2') def ar2(): return render_template('ar2.html') # Logout @app.route('/logout') @is_logged_in def logout(): session.clear() flash('ออกจากระบบสําเร็จ', 'success') return redirect(url_for('login')) if __name__ == '__main__': app.secret_key = '802a10465059f4276f654ab46b8033a2' app.config['SESSION_TYPE'] = 'filesystem' app.run(debug=True) <file_sep>/demo/shop-flask_mysql-master/shopfooddb.sql -- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 30, 2019 at 09:26 PM -- Server version: 10.1.37-MariaDB -- PHP Version: 7.3.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `shopfooddb` -- -- -------------------------------------------------------- -- -- Table structure for table `account` -- CREATE TABLE `account` ( `id` int(11) NOT NULL, `name` varchar(30) NOT NULL, `email` varchar(30) NOT NULL, `username` varchar(20) NOT NULL, `password` varchar(100) NOT NULL, `status` enum('admin','member') NOT NULL DEFAULT 'member', `phone` varchar(10) NOT NULL, `city` text NOT NULL, `register_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `account` -- INSERT INTO `account` (`id`, `name`, `email`, `username`, `password`, `status`, `phone`, `city`, `register_date`) VALUES (1, 'DDoS', '<EMAIL>', 'admin', '$5$rounds=535000$evqWjRUheq844jYZ$9x/2ICvmpVdRx.7hKh0NuWR07tfwXG0lvvGr9NddVV6', 'admin', '0611138083', '255/55 ม.18 อ.เมือง ต.ข้ามใหญ่ อ.เมือง จ.อุบล', '2019-03-19 14:01:25'), (2, '<NAME>', '<EMAIL>', 'DDoS', '$5$rounds=535000$gAYzjLdkxr3WeRBq$ofKaFUSpQTsjHyHtYg3VEy1Qa2xIWmiHKocLFm7s0C5', 'member', '0611138083', '-', '2019-03-19 19:09:17'), (3, 'fah', '<EMAIL>', 'fafafa', '$5$rounds=535000$kE5umvuTe3TyUQ/9$DfR6.8wDG0w.96pZZ0J6qWkNaAQmVPRfy4Y7V51WkS7', 'member', '0888888888', '-', '2019-03-26 08:11:45'), (4, 'James', '<EMAIL>', 'James', '$5$rounds=535000$atc4ADhE350WYonJ$Vgf70xpb4HjQ2qSv77TPbgjgK8D2AnOQEbaGS2g.vgD', 'member', '0123456789', '255/55 ม.18 อ.เมือง ต.ข้ามใหญ่ อ.เมือง จ.อุบล', '2019-03-30 05:50:28'), (5, 'gg', '<EMAIL>', 'greathoo', '$5$rounds=535000$J5EUEzEMqw3kELVw$ubHnNrY0tkdmaaYeEAbBhkSBI10Uk6Pkt8mxdYDilZ6', 'member', '0123456789', 'my home na ja', '2019-03-30 07:44:03'); -- -------------------------------------------------------- -- -- Table structure for table `data_mess` -- CREATE TABLE `data_mess` ( `id` int(11) NOT NULL, `status` enum('review','support','recommended') NOT NULL, `status_r` enum('unread','read') NOT NULL DEFAULT 'unread', `star` enum('1','2','3','4','5') NOT NULL, `user` varchar(100) NOT NULL, `email` varchar(50) NOT NULL, `title` varchar(100) NOT NULL, `menu` enum('สเต็กหมู','สเต็กปลา','สเต็กไก่','สเต็กซี่โครงหมู') NOT NULL, `messages` text NOT NULL, `comments_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `orderdb` -- CREATE TABLE `orderdb` ( `id` int(20) NOT NULL, `customer` varchar(100) NOT NULL, `menu` varchar(30) NOT NULL, `price` int(10) NOT NULL, `status` enum('Wait','Accept','Sending','completed') NOT NULL DEFAULT 'Wait', `city` varchar(50) NOT NULL, `order_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `orderdb` -- INSERT INTO `orderdb` (`id`, `customer`, `menu`, `price`, `status`, `city`, `order_date`) VALUES (1, 'greathoo', 'สเต็กหมู', 79, 'Sending', 'my home na ja', '2019-03-30 07:44:21'); -- -- Indexes for dumped tables -- -- -- Indexes for table `account` -- ALTER TABLE `account` ADD PRIMARY KEY (`id`); -- -- Indexes for table `data_mess` -- ALTER TABLE `data_mess` ADD PRIMARY KEY (`id`); -- -- Indexes for table `orderdb` -- ALTER TABLE `orderdb` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `account` -- ALTER TABLE `account` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `data_mess` -- ALTER TABLE `data_mess` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `orderdb` -- ALTER TABLE `orderdb` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/demo/shop-flask_mysql-master/app.py from flask import Flask, render_template, flash, redirect, url_for, session, request, logging #from data import import pymysql.cursors from passlib.hash import sha256_crypt from wtforms import Form, StringField, TextAreaField, PasswordField, validators from functools import wraps app = Flask(__name__) # Config MySQL MYSQL_HOST = 'localhost' MYSQL_USER = 'root' MYSQL_PASSWORD = '' MYSQL_DB = 'shopfooddb' #connection MySQL connection = pymysql.connect(host=MYSQL_HOST, user=MYSQL_USER, password=<PASSWORD>PASSWORD, db=MYSQL_DB , cursorclass=pymysql.cursors.DictCursor) # Index @app.route('/') def index(): return render_template('home.html') @app.route('/review') def review(): cur = connection.cursor() result = cur.execute("SELECT * FROM data_mess WHERE status = 'review' ") data = cur.fetchall() return render_template('review.html', data=data, result=result) # history @app.route('/history') def history(): # Create cursor cur = connection.cursor() # Get history result = cur.execute("SELECT * FROM orderdb") history = cur.fetchall() if result > 0: return render_template('history.html', history=history) else: msg = 'No History Found' return render_template('history.html', msg=msg) # Close connection cur.close() # Register Form Class class RegisterForm(Form): name = StringField('Name', [validators.Length(min=1, max=50)]) username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email', [validators.Length(min=6, max=50)]) phone = StringField('Phone', [validators.Length(min=10, max=10)]) city = StringField('City', [validators.Length(min=9, max=100)]) password = PasswordField('Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords do not match') ]) confirm = PasswordField('Confirm Password') # User Register @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): name = form.name.data email = form.email.data phone = form.phone.data city = form.city.data username = form.username.data password = sha256_crypt.encrypt(str(form.password.data)) # Create cursor cur = connection.cursor() x = cur.execute("SELECT * FROM account WHERE username = %s",(username)) if int(x) > 0: flash("That username is already taken, please choose another", 'danger') return render_template('register.html', form=form) # Execute query cur.execute("INSERT INTO account(name, email, username, password, phone, city) VALUES(%s, %s, %s, %s, %s, %s)", (name, email, username, password, phone, city)) # Commit to DB connection.commit() # Close connection cur.close() flash('You are now registered and can log in', 'success') return redirect(url_for('login')) return render_template('register.html', form=form) # User login @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # Get Form Fields username = request.form['username'] password_candidate = request.form['<PASSWORD>'] # Create cursor cur = connection.cursor() # Get user by username result = cur.execute("SELECT * FROM account WHERE username = %s", [username]) if result > 0: # Get stored hash data = cur.fetchone() password = data['password'] status = data['status'] city = data['city'] email = data['email'] # Compare Passwords if sha256_crypt.verify(password_candidate, password): # Passed session['logged_in'] = True session['username'] = username session['status'] = status session['city'] = city session['email'] = email flash('You are now logged in', 'success') return redirect(url_for('Menu')) else: error = 'Invalid login' return render_template('login.html', error=error) # Close connection cur.close() else: error = 'Wrong username or password !!!' return render_template('login.html', error=error) return render_template('login.html') # Check if user logged in def is_logged_in(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: flash('Only Member, Please login !!!', 'danger') return redirect(url_for('login')) return wrap # Logout @app.route('/logout') @is_logged_in def logout(): session.clear() flash('You are now logged out', 'success') return redirect(url_for('login')) # Dashboard @app.route('/dashboard') @is_logged_in def dashboard(): date = ['Wait','Accept','Sending','completed'] stt_W = [] stt_Acc = [] stt_Sd = [] stt_cp = [] row = 0 for status in date: row+=1 cur = connection.cursor() result = cur.execute("SELECT * FROM orderdb WHERE status = %s", [status] ) stt_date = cur.fetchall() if row == 1: stt_W.append(result) stt_W.append(stt_date) elif row == 2: stt_Acc.append(result) stt_Acc.append(stt_date) elif row == 3: stt_Sd.append(result) stt_Sd.append(stt_date) elif row == 4: stt_cp.append(result) stt_cp.append(stt_date) acctotal = cur.execute("SELECT * FROM account") cmmtotal = cur.execute("SELECT * FROM data_mess") innMoney = 0 for s1 in stt_cp[1]: innMoney += s1['price'] if stt_W[0] > 0: msg = 'New order '+str(stt_W[0]) return render_template('dashboard.html', msg=msg, cmmtotal=cmmtotal, innMoney=innMoney, acctotal=acctotal, stt_W=stt_W, stt_Acc=stt_Acc, stt_Sd=stt_Sd, stt_cp=stt_cp) else: msg = 'No Order Wait' return render_template('dashboard.html', msg=msg, cmmtotal=cmmtotal, innMoney=innMoney, acctotal=acctotal, stt_W=[0], stt_Acc=stt_Acc, stt_Sd=stt_Sd, stt_cp=stt_cp) # Close connection cur.close() #show menu @app.route('/menu/') @is_logged_in def Menu(): return render_template('showmenu.html') @app.route('/myorder/') @is_logged_in def myorder(): customer = session['username'] cur = connection.cursor() result = cur.execute("SELECT * FROM orderdb WHERE customer = %s And status = %s", [customer,"Wait"] ) history = cur.fetchall() cur.close() return render_template('myorder.html', history=history, result=result) @app.route('/myhistory/') @is_logged_in def myhistory(): customer = session['username'] cur = connection.cursor() result = cur.execute("SELECT * FROM orderdb WHERE customer = %s", [customer] ) history = cur.fetchall() cur.close() return render_template('myhistory.html', history=history, result=result) @app.route('/setting') @is_logged_in def setting(): username = session['username'] cur = connection.cursor() cur.execute("SELECT * FROM account WHERE username = %s", [username]) data = cur.fetchall() cur.close() return render_template('setting.html',data=data) @app.route('/addorder/<string:id>',methods=['GET']) @is_logged_in def addorder(id): datafood = { '0':["สเต็กหมู",79] } customer = session['username'] city = session['city'] print(city) data = datafood[id] cur = connection.cursor() sql="Insert into `orderdb` (`customer`,`menu`,`price`,`city`) values(%s,%s,%s,%s)" cur.execute(sql,(customer,data[0],data[1],city)) connection.commit() cur.close() flash("การสังซื้อสําเร็จ","success") return redirect(url_for('myorder')) @app.route('/upstatus/<string:id_order>',methods=['GET']) @is_logged_in def upstatus(id_order): cur = connection.cursor() cur.execute("SELECT * FROM orderdb WHERE id = %s", [id_order]) data_id = cur.fetchall() data_check = data_id[0] if data_check['status'] == "Wait": cur.execute("UPDATE orderdb SET status = 'Accept' WHERE id = %s", [data_check['id']]) connection.commit() elif data_check['status'] == "Accept": cur.execute("UPDATE orderdb SET status = 'Sending' WHERE id = %s", [data_check['id']]) connection.commit() elif data_check['status'] == "Sending": cur.execute("UPDATE orderdb SET status = 'completed' WHERE id = %s", [data_check['id']]) connection.commit() cur.close() return redirect(url_for('dashboard')) @app.route('/delete/<string:id_delete>',methods=['GET']) @is_logged_in def delete(id_delete): cur = connection.cursor() cur.execute("delete FROM orderdb WHERE id = %s",[id_delete]) connection.commit() cur.close() return redirect(url_for('dashboard')) @app.route('/update',methods=['POST']) @is_logged_in def update(): try: username = session['username'] if request.method=="POST": name = request.form['name'] phone = request.form['phone'] email = request.form['email'] city = request.form['city'] #conn db cur = connection.cursor() sql = "update account set name = %s, email = %s, phone = %s, city = %s where username = %s" cur.execute(sql,(name, email, phone, city, username)) connection.commit cur.close flash("ข้อมูลได้รับการอัพเดทเรียร้อยแล้ว","success") return redirect(url_for('setting')) except Exception as Error: error = str(Error) return render_template('setting.html',error=error) @app.route('/formreview') @is_logged_in def formreview(): return render_template('addreview.html') @app.route('/addreview',methods=['POST']) @is_logged_in def addreview(): try: status = 'review' user = session['username'] email = session['email'] if request.method=="POST": title = request.form['title'] mess = request.form['mess'] star = request.form['star'] #conn db cur = connection.cursor() sql="Insert into `data_mess` (`status`,`star`,`user`,`email`,`title`,`messages`) values(%s,%s,%s,%s,%s,%s)" cur.execute(sql,(status,star,user,email,title,mess)) cur.close connection.commit() flash("คุณได้เขี่ยนรีวิวแล้ว","success") return redirect(url_for('review')) except Exception as Error: error = str(Error) return render_template('addreview.html',error=error) if __name__ == '__main__': app.secret_key='DDoS' app.run(debug=True) <file_sep>/server.py from flask import Flask, render_template, flash, redirect, url_for, session, request, logging #from data import import pymysql.cursors from passlib.hash import sha256_crypt from wtforms import Form, StringField, TextAreaField, PasswordField, validators from functools import wraps from werkzeug.utils import secure_filename import os # from flask_mail import Mail, Message import smtplib from random import randint app = Flask(__name__) SMTP_HOST = "smtp.gmail.com" SMTP_PORT = 587 # Config MySQL MYSQL_HOST = '172.16.17.32' MYSQL_USER = 'master' MYSQL_PASSWORD = '<PASSWORD>' MYSQL_DB = 'University' app.config['IMAGE_UPLOAD'] = "static/image/" app.config['ALLOWED_IMAGE_EXTENTIONS'] = ["PNG", "JPG", "JPEG", "GIF"] # mail_settings = { # "MAIL_SERVER": 'smtp.gmail.com', # "MAIL_PORT": 587, # "MAIL_USE_TLS": False, # "MAIL_USE_SSL": False, # "MAIL_USERNAME": '<EMAIL>', # "MAIL_PASSWORD": '<PASSWORD>' # } # app.config.update(mail_settings) # mail = Mail(app) # connection MySQL connection = pymysql.connect(host=MYSQL_HOST, user=MYSQL_USER, password=<PASSWORD>, db=MYSQL_DB , cursorclass=pymysql.cursors.DictCursor) # Index @app.route('/') def landing(): cur = connection.cursor() cur.execute("SELECT * FROM residents") datas = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM all_location") all = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM reviews ORDER BY rating DESC") top = cur.fetchall() cur.close() return render_template('map.html', datas=datas, all=all, top=top) @app.route('/index') def index(): cur = connection.cursor() cur.execute("SELECT * FROM residents") datas = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM all_location") all = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM reviews ORDER BY rating DESC") top = cur.fetchall() cur.close() return render_template('map.html', datas=datas, all=all, top=top) @app.route('/admin', methods=['GET', 'POST']) def Addmin(): cur = connection.cursor() cur.execute("SELECT * FROM members") members = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM residents") residents = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM all_location") all = cur.fetchall() cur.close() cur = connection.cursor() cur.execute("SELECT * FROM reviews") reviews = cur.fetchall() cur.close() cur = connection.cursor() total_residents = cur.execute("SELECT * FROM residents") cur.close() cur = connection.cursor() total_comments = cur.execute("SELECT * FROM reviews") cur.close() cur = connection.cursor() total_users = cur.execute("SELECT * FROM members") cur.close() return render_template('Admin.html',members=members, residents=residents, all=all, reviews=reviews,total_residents=total_residents, total_comments=total_comments ,total_users=total_users) @app.route('/OTP', methods=['GET', 'POST']) def OTP(): if request.method == 'POST': cur = connection.cursor() checkOTP = cur.execute("SELECT * FROM otp WHERE email = %s AND OTP = %s",(request.form['email'], request.form['OTP'])) print(checkOTP) if int(checkOTP) > 0: verify = cur.execute("UPDATE members SET verify = %s WHERE email = %s",("verify",request.form['email'])) delOTP = cur.execute("DELETE FROM otp WHERE email = %s",(request.form['email'])) connection.commit() flash('Verify Success', 'success') cur.close() return redirect(url_for('login')) else : return render_template('OTP',email=request.form['email']) return render_template('OTP.html') @app.route('/about-team') def about_team(): return render_template('landing.html') @app.route('/select') def selectType(): return render_template('select.html') # Register Form Class class RegisterForm(Form): email = StringField('email', [ validators.Regexp('[\w.+\-]+@ubu.ac\.th$', message="กรุณาใช้<EMAIL>"), ]) fname = StringField('firstName', [validators.Length(min=6, max=50)]) lastName = StringField('lastName', [validators.Length(min=6, max=50)]) password = <PASSWORD>Field('<PASSWORD>', [ validators.DataRequired(), validators.EqualTo('confirm', message='<PASSWORD>') ]) confirm = PasswordField('Confirm Password') def random_with_N_digits(n): range_start = 10**(n-1) range_end = (10**n)-1 return randint(range_start, range_end) # User Register @app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm(request.form) if request.method == 'POST' and form.validate(): with smtplib.SMTP(host=SMTP_HOST, port=SMTP_PORT) as server: email = form.email.data password = <PASSWORD>(str(form.password.data)) fname = form.fname.data lastName = form.lastName.data # Create cursor cur = connection.cursor() x = cur.execute("SELECT * FROM members WHERE email = %s",(email)) if int(x) > 0: # flash("That username is already taken, please choose another", 'danger') return render_template('login.html', form=form) # Execute query cur.execute("INSERT INTO members(email, password, firstName, lastName) VALUES(%s, %s, %s, %s)", (email, password, fname, lastName)) # Commit to DB connection.commit() # Close connection cur.close() flash('You are now registered and can log in', 'success') OTP = random_with_N_digits(5) cur = connection.cursor() cur.execute("INSERT INTO otp(OTP, email) VALUES(%s, %s)", (OTP, email)) connection.commit() cur.close() flash('Send OTP Success', 'success') msg = f"From: <EMAIL>\r\nTo: {form.email.data}\r\nSubject: OTP: < {OTP} >\r\n" server.starttls() server.login('<EMAIL>', 'love@123456') server.sendmail('<EMAIL>', form.email.data, msg) return render_template('OTP.html',email=form.email.data) return render_template('login.html', form=form) # User login @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': # Get Form Fields email = request.form['username'] password_candidate = request.form['<PASSWORD>'] # Create cursor cur = connection.cursor() # Get user by username result = cur.execute("SELECT * FROM members WHERE email = %s", [email]) data = cur.fetchone() if result > 0 and data['verify'] == "verify": # Get stored hash userId = data['userId'] password = data['<PASSWORD>'] email = data['email'] firstName = data['firstName'] lastName = data['lastName'] permission = data['permission'] # Compare Passwords if sha256_crypt.verify(password_candidate, password): # Passed session['logged_in'] = True session['userId'] = userId session['email'] = email session['firstName'] = firstName session['lastName'] = lastName session['permission'] = permission flash('You are now logged in', 'success') return redirect(url_for('index')) else: error = 'Invalid login' return redirect(url_for('register', error=error)) # Close connection cur.close() else: error = 'Wrong username or password !!!' return redirect(url_for('register', error=error)) return redirect(url_for('register')) # Check if user logged in def is_logged_in(f): @wraps(f) def wrap(*args, **kwargs): if 'logged_in' in session: return f(*args, **kwargs) else: return redirect(url_for('login')) return wrap # Logout @app.route('/logout') @is_logged_in def logout(): session.clear() flash('You are now logged out', 'success') return redirect(url_for('login')) @app.route('/adds/<string:types>', methods=['GET', 'POST']) def adds(types): return render_template("adds.html",types=types) @app.route('/insert_location', methods=['POST']) def insert_location(): if request.method == 'POST': user_id = request.form['addformuser'] names = request.form['name'] lat = request.form['lat'] lng = request.form['lng'] types = request.form['types'] cur = connection.cursor() x = cur.execute("SELECT * FROM all_location WHERE name = %s",[names]) if int(x) > 0: flash("มีคนได้เพิ่มสถานที่นี้ไปแล้วพักนี้ไปแล้ว", 'danger') cur.close() cur.execute("INSERT INTO all_location(addformuser ,name, lat, lng, types) VALUES(%s, %s, %s, %s, %s)", (user_id ,names, lat, lng, types)) connection.commit() cur.close() flash("ได้ทําการเพิ่มข้อมูลเรียบร้อยแล้ว", 'danger') return redirect(url_for('index')) @app.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'POST': user_id = request.form['addformuser'] residentName = request.form['residentName'] lat = request.form['lat'] lng = request.form['lng'] roomType = request.form['roomType'] price = request.form['price'] details = request.form['details'] phoneConnect = request.form['phoneConnect'] OtherConnect = request.form['OtherConnect'] image = request.files['image'] air = request.form['air'] fan = request.form['fan'] water_heater = request.form['water_heater'] furniture = request.form['furniture'] cable_tv = request.form['cable_tv'] phone_direct = request.form['phone_direct'] internet = request.form['internet'] pet = request.form['pet'] smoking = request.form['smoking'] parking = request.form['parking'] elevators = request.form['elevators'] security = request.form['security'] keycard = request.form['keycard'] cctv = request.form['cctv'] pool = request.form['pool'] fitness = request.form['fitness'] laundry = request.form['laundry'] hair_salon = request.form['hair_salon'] filename = secure_filename(image.filename) image.save(os.path.join(app.config["IMAGE_UPLOAD"], filename)) cur = connection.cursor() x = cur.execute("SELECT * FROM residents WHERE residentName = %s",[residentName]) if int(x) > 0: flash("มีคนได้เพิ่มหอพักนี้ไปแล้ว", 'danger') cur.close() cur.execute("INSERT INTO residents(addformuser, residentName, lat, lng, roomType, price, details, phoneConnect, OtherConnect, image, air, fan, water_heater, furniture, cable_tv, phone_direct, internet, pet, smoking, parking, elevators, security, keycard, cctv, pool, fitness, laundry, hair_salon) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (user_id, residentName, lat, lng, roomType, price, details, phoneConnect, OtherConnect, filename, air, fan, water_heater, furniture, cable_tv, phone_direct, internet, pet, smoking, parking, elevators, security, keycard, cctv, pool, fitness, laundry, hair_salon)) connection.commit() cur.close() flash('resident saved', 'success') connection.commit() cur.close() return render_template("add.html") @app.route('/resident/<string:id>',methods=['GET', 'POST']) def resident(id): cur = connection.cursor() result = cur.execute("SELECT * FROM residents WHERE residentId = %s", [id]) datas = cur.fetchall() cur.close() cur = connection.cursor() result = cur.execute("SELECT * FROM reviews") reviews = cur.fetchall() cur.close() if request.method == 'POST': print(request.form) cur = connection.cursor() cur.execute("INSERT INTO reviews(comments, rating, userId, residentId) VALUES(%s, %s, %s, %s)", (request.form['comments'], request.form['rating'], request.form['userId'], request.form['residentId'])) connection.commit() cur.close() return render_template("resident.html",datas=datas ,id=id,reviews=reviews) @app.route('/delete/<string:path>/<string:id_delete>',methods=['GET']) @is_logged_in def delete(path,id_delete): cur = connection.cursor() if path == "members": cur.execute("delete FROM members WHERE userId = %s",[id_delete]) elif path == "all_location": cur.execute("delete FROM all_location WHERE id = %s",[id_delete]) elif path == "residents": cur.execute("delete FROM residents WHERE residentId = %s",[id_delete]) elif path == "reviews": cur.execute("delete FROM reviews WHERE reviewId = %s",[id_delete]) connection.commit() cur.close() return redirect(url_for('Addmin')) @app.route('/setting') @is_logged_in def setting(): username = session['userId'] cur = connection.cursor() cur.execute("SELECT * FROM members WHERE userId = %s", [username]) data = cur.fetchall() cur.close() return render_template('setting.html',data=data) @app.route('/update',methods=['POST']) @is_logged_in def update(): try: userId = session['userId'] if request.method=="POST": firstName = request.form['firstName'] lastName = request.form['lastName'] email = request.form['email'] #conn db cur = connection.cursor() sql = "update members set firstName = %s, lastName = %s, email = %s where userId = %s" cur.execute(sql,(firstName, lastName, email, userId)) connection.commit cur.close flash("ข้อมูลได้รับการอัพเดทเรียร้อยแล้ว","success") return redirect(url_for('setting')) except Exception as Error: error = str(Error) print(error) return redirect(url_for('setting')) if __name__ == '__main__': app.secret_key='<KEY>n[dnfbpndp[b' app.run(debug=True, host="172.16.17.32") <file_sep>/README.md # Love-s-University Love's University <file_sep>/demo/shop-flask_mysql-master/requirements.txt PyMySQL==0.9.3 Flask==1.0.2 passlib==1.7.1 Flask-WTF==0.14.2 Flask-Login==0.4.1
2baf98dc6283d9bc0d1ba488f2b339cd97539250
[ "Markdown", "SQL", "Python", "Text" ]
6
Python
DDoS000/Love-s-University
23dd31fd9a879731cf4d75647c3bf27a949e6288
3a3f3be4a6a1df3efb1b540a218d7d7089ce2902
refs/heads/master
<repo_name>gunnarmorling/constraint-validation<file_sep>/README.md # JPA ConstraintViolationException example This example tries to demonstrate, that the default message found in `javax.validation.ConstraintViolationException` does not provide enough context information to be usable in log statements for analysing the `javax.validation.ConstraintViolation` involved. ## Setup This project uses Spring Boot, Spring Data JPA, EclipseLink, H2 and Hibernate Validator to demonstrate a constraint violation on a simple Person entity. It provides a Gradle based build system and should be easily accessible in your favourite IDE. ## Run the test ``` $ ./gradlew clean build ``` <file_sep>/src/main/java/jensfischerhh/constraintvalidation/ConstraintViolationExceptionMessageEnricher.java package jensfischerhh.constraintvalidation; import java.util.stream.Collectors; import javax.validation.ConstraintViolationException; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.support.PersistenceExceptionTranslator; /** * Translates {@link ConstraintViolationException}s into {@link DataIntegrityViolationException}s, adding * property path and message for all contained constraint violations to the exception message. * * @author <NAME> */ public class ConstraintViolationExceptionMessageEnricher implements PersistenceExceptionTranslator { @Override public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex instanceof ConstraintViolationException) { String message = ex.getMessage() + System.lineSeparator(); message += ( (ConstraintViolationException) ex ).getConstraintViolations() .stream() .map( cv -> cv.getPropertyPath() + ": " + cv.getMessage() ) .collect( Collectors.joining( ";" + System.lineSeparator() ) ); return new DataIntegrityViolationException( message, ex ); } return null; } }
e6b6828ad3d3debf73ec8df17a758af1ec448e34
[ "Markdown", "Java" ]
2
Markdown
gunnarmorling/constraint-validation
921e16bd93c91b1c30d967f868719886bc29bd41
c46f12c48220b358ef99f8200d35248e28d1859c
refs/heads/master
<file_sep>(function($) { "use strict"; $('.nav_toggle').on('click', function(){ $(".navigation_menu").toggleClass("menu_open"); $(this).toggleClass("close_toggle"); }); //dropdown menu $(".navigation_menu ul li ul.sub_menu").parents("li").addClass("dropdown_toggle"); $(".dropdown_toggle").append("<span class='caret_down'></span>"); $(".navigation_menu ul li").children(".caret_down").on("click",function(){ $(this).toggleClass("caret_up"); $(this).prev("ul").slideToggle(); }); $(".megamenu_wrapper").parents("li").addClass("mega_dropdown"); $(".mega_dropdown > a").append("<span class='mega_toggle'><i class='fa fa-angle-down'></span>"); //mega menu js script var win_w = $(window).outerWidth(); if(win_w < 992){ $(".mega_dropdown").on('click', function(){ $(this).children(".megamenu_wrapper").slideToggle(300); }); } //fix header on scroll var win_scroll = $(window).scrollTop(); $(window).on('bind scroll', function(e) { if ($(window).scrollTop() > 300) { $('.navigation_header').addClass('fixed_menu'); } else { $('.navigation_header').removeClass('fixed_menu'); } }); //blog slider if ($(".home_slider").length > 0){ $(".home_slider").owlCarousel({ singleItem:true, items:1, loop:true, margin:10, autoplay:false, autoplayTimeout:3000, autoplaySpeed:1500, smartSpeed:1500, dots:false, nav:true, navText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], }); } //video carousel if ($(".related_post_carousel").length > 0){ $(".related_post_carousel").owlCarousel({ singleItem:true, items:4, loop:true, margin:10, autoplay:false, autoplayTimeout:3000, autoplaySpeed:1500, smartSpeed:1500, dots:false, nav:true, navText:["<i class='fa fa-angle-left'></i>","<i class='fa fa-angle-right'></i>"], responsiveClass: true, responsive : { 0 : { items: 1 }, 768 : { items: 2 }, 992 : { items: 3 }, 1199 : { items: 4 }, } }); } //onclick popup js $('.popup_icon').on('click', function() { $('.popup_wrapper').removeClass("open_popup"); var popup_show = $(this).attr('data-show'); $('#'+ popup_show).addClass("open_popup"); }); $('.popup_wrapper').on('click', function(){ $(this).removeClass("open_popup"); }); $('.close_btn').on('click', function(){ $('.popup_wrapper').removeClass("open_popup"); }); $('.popup_inner_content').on('click', function(e){ e.stopPropagation(); }); //load event $(window).on('load', function() { $(".ayu_loader").delay(600).fadeOut("slow"); //add class on focused in input $(".input").each(function() { var default_val = $(this).val(); if ( default_val !== "") { $(this).parents('.form_group').addClass('focused'); } else{ $(this).parents('.form_group').removeClass('focused'); } }); }); //add class on focus in label $('.input').focus(function(){ $(this).parents('.form_group').addClass('focused'); }); //Remove class on focus in label $('.input').blur(function(){ var inputValue = $(this).val(); if ( inputValue == "" ) { $(this).parents('.form_group').removeClass('focused'); } }); //blog slideToggle $('.blog_filter_btn').on('click', function(){ $(".blog_sidebar").slideToggle(200); }); })(jQuery);
2ce6b87d1658d043ddae442cdcf3b580f16167c7
[ "JavaScript" ]
1
JavaScript
devendrasinghoxy/rudraspeaks
867d64c51d806033b59a8cf219016d565ddf5e89
7b5720805b1712917f45d0a70aa4056214c511e2
refs/heads/master
<repo_name>andrerosamatos/LEDA<file_sep>/R09/src/main/java/adt/hashtable/open/HashtableOpenAddressLinearProbingImpl.java package adt.hashtable.open; import adt.hashtable.hashfunction.HashFunctionClosedAddressMethod; import adt.hashtable.hashfunction.HashFunctionLinearProbing; public class HashtableOpenAddressLinearProbingImpl<T extends Storable> extends AbstractHashtableOpenAddress<T> { public HashtableOpenAddressLinearProbingImpl(int size, HashFunctionClosedAddressMethod method) { super(size); hashFunction = new HashFunctionLinearProbing<T>(size, method); this.initiateInternalTable(size); } @Override public void insert(T element) { int probe = 0; boolean adicionou = false; while (probe <= this.size() && adicionou == false) { int index = ((HashFunctionLinearProbing<T>) this.hashFunction).hash(element, probe); if (this.table[index] == null || this.table[index].equals(deletedElement)) { this.table[index] = element; elements++; adicionou = true; } else { probe++; COLLISIONS++; } } if (probe > size()) { throw new HashtableOverflowException(); } } @Override public void remove(T element) { int probe = 0; boolean removeu = false; if (element != null) { while (probe <= size() && removeu == false) { int index = ((HashFunctionLinearProbing<T>) this.hashFunction).hash(element, probe); if (this.table[index] != null && this.table[index].equals(element) ) { this.table[index] = deletedElement; removeu = true; elements--; } else { probe++; } } } } @Override public T search(T element) { boolean achou = false; int probe = 0; T elemento = null; while (probe <= size() && achou == false) { int index = ((HashFunctionLinearProbing<T>) this.hashFunction).hash(element, probe); if (this.table[index] != null && this.table[index].equals(element)) { achou = true; elemento = element; } else { probe++; } } return elemento; } @Override public int indexOf(T element) { boolean achou = false; int probe = 0; int indice = -1; while (probe <= size() && achou == false) { int index = ((HashFunctionLinearProbing<T>) this.hashFunction).hash(element, probe); if (this.table[index].equals(element)) { achou = true; indice = index; } else { probe++; } } return indice; } } <file_sep>/RR3-01/Potência Recursiva/src/main/Main.java package main; public class Main { public static void main(String[] args) { int expoente = 10; int valor = 2; System.out.println(potencia(valor, expoente)); } public static long potencia(int valor, int expoente) { int result = 1; int i = 1; return potencia(valor, expoente, i, result); } private static long potencia(int valor, int expoente, int i, int result) { if (i <= expoente) { result = (int) (valor * potencia(valor, expoente, i + 1, result)); } return result; } } <file_sep>/R07/src/main/java/adt/linkedList/RecursiveSingleLinkedListImpl.java package adt.linkedList; public class RecursiveSingleLinkedListImpl<T> implements LinkedList<T> { protected T data; protected RecursiveSingleLinkedListImpl<T> next; public RecursiveSingleLinkedListImpl() { } public RecursiveSingleLinkedListImpl(T data, RecursiveSingleLinkedListImpl<T> next) { this.data = data; this.next = next; } @Override public boolean isEmpty() { boolean isEmpty = false; if (data == null) { isEmpty = true; } return isEmpty; } @Override public int size() { int tamanho = 0; if (!isEmpty()) { tamanho = (this.next.size() + 1); } else { return 0; } return tamanho; } @Override public T search(T element) { T elemento = null; if (!isEmpty()) { if (data.equals(element)) { elemento = element; } else { elemento = next.search(element); } } return elemento; } @Override public void insert(T element) { if(isEmpty()) { data = element; next = new RecursiveSingleLinkedListImpl<>(); } else { next.insert(element); } } @Override public void remove(T element) { if (search(element) != null) { if(data.equals(element)) { data = next.data; next = next.next; } else { next.remove(element); } } } @Override public T[] toArray() { T[] result = (T[]) new Object[size()]; int count = 0; return toArray(result, count); } private T[] toArray(T[] result, int count) { if (!isEmpty()) { result[count] = data; result = next.toArray(result, count + 1); } return result; } public T getData() { return data; } public void setData(T data) { this.data = data; } public RecursiveSingleLinkedListImpl<T> getNext() { return next; } public void setNext(RecursiveSingleLinkedListImpl<T> next) { this.next = next; } } <file_sep>/R02/src/main/java/sorting/divideAndConquer/MergeSort.java package sorting.divideAndConquer; import java.util.ArrayList; import java.util.List; import sorting.AbstractSorting; /** * Merge sort is based on the divide-and-conquer paradigm. The algorithm * consists of recursively dividing the unsorted list in the middle, sorting * each sublist, and then merging them into one single sorted list. Notice that * if the list has length == 1, it is already sorted. */ public class MergeSort<T extends Comparable<T>> extends AbstractSorting<T> { @Override public void sort(T[] array, int leftIndex, int rightIndex) { int meio; if (leftIndex < rightIndex) { meio = (leftIndex + rightIndex) / 2; sort(array, leftIndex, meio); sort(array, meio + 1, rightIndex); intercala(array, leftIndex, meio, rightIndex); } } public void intercala(T[] array, int leftIndex, int meio, int rightIndex) { int i, j, k; T vetorB[] = array[][array.length]; for (i = leftIndex; i < meio; i++) { vetorB[i] = (int) array[i]; } for (j = meio + 1; j < rightIndex; j++) { vetorB[rightIndex + meio + 1 - j] = (int) array[j]; } i = leftIndex; j = rightIndex; for (k = leftIndex; k < rightIndex; k++) { if (vetorB[i] <= vetorB[j]) { array[k] = vetorB[i]; i = i + 1; } else { array[k] = vetorB[j]; j = j - 1; } } } } <file_sep>/R06/src/main/java/adt/linkedList/DoubleLinkedListImpl.java package adt.linkedList; public class DoubleLinkedListImpl<T> extends SingleLinkedListImpl<T> implements DoubleLinkedList<T> { protected DoubleLinkedListNode<T> last; public DoubleLinkedListImpl() { head = new DoubleLinkedListNode(); last = (DoubleLinkedListNode<T>) head; } @Override public void insertFirst(T element) { DoubleLinkedListNode newHead = new DoubleLinkedListNode<>(); newHead.next = head; newHead.previous = null; head.previous = newHead; } @Override public void removeFirst() { if(isEmpty()) { } else { if (previous.isEmpty) { } } } @Override public void removeLast() { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } public DoubleLinkedListNode<T> getLast() { return last; } public void setLast(DoubleLinkedListNode<T> last) { this.last = last; } } <file_sep>/PP2/src/main/java/adt/linkedList/batch/BatchLinkedListImpl.java package adt.linkedList.batch; import javax.swing.plaf.nimbus.NimbusLookAndFeel; import adt.linkedList.DoubleLinkedList; import adt.linkedList.DoubleLinkedListImpl; import adt.linkedList.DoubleLinkedListNode; import adt.linkedList.SingleLinkedListNode; import util.GenericException; /** * Manipula elementos da LinkedList em bloco (batch). * * @author campelo * @author adalberto * * @param <T> */ public class BatchLinkedListImpl<T> extends DoubleLinkedListImpl<T> implements BatchLinkedList<T> { /* * Nao modifique nem remova este metodo. */ public BatchLinkedListImpl() { head = new DoubleLinkedListNode<T>(); last = (DoubleLinkedListNode<T>) head; } @Override public void inserirEmBatch(int posicao, T[] elementos) throws GenericException { if (posicao < 0 || posicao > this.size() || elementos == null) { throw new GenericException(); } else { DoubleLinkedListNode<T> cNode = (DoubleLinkedListNode<T>) elementos[0]; cNode.setPrevious(null); DoubleLinkedListNode<T> dNode = null; DoubleLinkedListNode<T> fNode = (DoubleLinkedListNode<T>) elementos[1]; DoubleLinkedListNode<T> eNode = null; DoubleLinkedList<T> lista = null; for (int i = 1; i < elementos.length - 1; i++) { dNode = (DoubleLinkedListNode<T>) elementos[i]; eNode = (DoubleLinkedListNode<T>) elementos[i + 1]; dNode.setNext(eNode); eNode.setPrevious(dNode); } cNode.setNext(fNode); fNode.setPrevious(cNode); eNode.setNext(null); int count = -1; DoubleLinkedListNode<T> aux = null; DoubleLinkedListNode<T> proximo = null; while (count != posicao) { aux = (DoubleLinkedListNode<T>) head.getNext(); proximo = (DoubleLinkedListNode<T>) aux.getNext(); count++; } aux.setNext(cNode); cNode.setPrevious(aux); eNode.setNext(proximo); proximo.setPrevious(eNode); } } @Override public void removerEmBatch(int posicao, int quantidade) throws GenericException { if (posicao < 0 || posicao > this.size() || quantidade > this.size()) { throw new GenericException(); } else { int count = -1; DoubleLinkedListNode<T> aux = null; DoubleLinkedListNode<T> proximo = null; while (count != posicao) { aux = (DoubleLinkedListNode<T>) head.getNext(); proximo = (DoubleLinkedListNode<T>) aux.getNext(); count++; } while (quantidade > 1) { proximo = (DoubleLinkedListNode<T>) proximo.getNext(); quantidade--; } if (proximo.getNext().isNIL()) { aux.setNext(null); } else { aux.setNext(proximo.getNext()); proximo = (DoubleLinkedListNode<T>) proximo.getNext(); proximo.setPrevious(aux); } } } /* * NAO MODIFIQUE NEM REMOVA ESTE METODO!!! * * Use este metodo para fazer seus testes * * Este metodo monta uma String contendo os elementos do primeiro ao ultimo, * comecando a navegacao pelo Head */ public String toStringFromHead() { String result = ""; DoubleLinkedListNode<T> aNode = (DoubleLinkedListNode<T>) getHead(); while (!aNode.isNIL()) { if (!result.isEmpty()) { result += " "; } result += aNode.getData(); aNode = (DoubleLinkedListNode<T>) aNode.getNext(); } return result; } /* * NAO MODIFIQUE NEM REMOVA ESTE METODO!!! * * Use este metodo para fazer seus testes * * Este metodo monta uma String contendo os elementos do primeiro ao ultimo, * porem comecando a navegacao pelo Last * * Este metodo produz o MESMO RESULTADO de toStringFromHead() * */ public String toStringFromLast() { String result = ""; DoubleLinkedListNode<T> aNode = getLast(); while (!aNode.isNIL()) { if (!result.isEmpty()) { result = " " + result; } result = aNode.getData() + result; aNode = (DoubleLinkedListNode<T>) aNode.getPrevious(); } return result; } @Override public String toString() { return toStringFromHead(); } } <file_sep>/R06/src/main/java/adt/queue/QueueDoubleLinkedListImpl.java package adt.queue; import adt.linkedList.DoubleLinkedList; import adt.linkedList.DoubleLinkedListImpl; public class QueueDoubleLinkedListImpl<T> implements Queue<T> { protected DoubleLinkedList<T> list; protected int size; public QueueDoubleLinkedListImpl(int size) { this.size = size; this.list = new DoubleLinkedListImpl<T>(); } @Override public void enqueue(T element) throws QueueOverflowException { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } @Override public T dequeue() throws QueueUnderflowException { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } @Override public T head() { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } @Override public boolean isEmpty() { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } @Override public boolean isFull() { // TODO Auto-generated method stub throw new UnsupportedOperationException("Not implemented yet!"); } } <file_sep>/R07/src/main/java/adt/linkedList/RecursiveDoubleLinkedListImpl.java package adt.linkedList; public class RecursiveDoubleLinkedListImpl<T> extends RecursiveSingleLinkedListImpl<T> implements DoubleLinkedList<T> { protected RecursiveDoubleLinkedListImpl<T> previous; public RecursiveDoubleLinkedListImpl() { } public RecursiveDoubleLinkedListImpl(T data, RecursiveSingleLinkedListImpl<T> next, RecursiveDoubleLinkedListImpl<T> previous) { super(data, next); this.previous = previous; } @Override public void insertFirst(T element) { if (isEmpty()) { data = element; next = new RecursiveDoubleLinkedListImpl<>(); } else { RecursiveDoubleLinkedListImpl<T> aux = new RecursiveDoubleLinkedListImpl<T>(data, next, this); data = element; next = aux; } } @Override public void removeFirst() { if (!isEmpty()) { data = next.data; next = next.next; } } @Override public void removeLast() { removeLast(this); } private void removeLast(RecursiveSingleLinkedListImpl<T> node) { if (next.next == null) { next = next.next; } else { removeLast(this.next); } } public RecursiveDoubleLinkedListImpl<T> getPrevious() { return previous; } public void setPrevious(RecursiveDoubleLinkedListImpl<T> previous) { this.previous = previous; } }
dad82bfd7652439324487408b9a3556c10383154
[ "Java" ]
8
Java
andrerosamatos/LEDA
162efade0c1ad77b1290fccaebed9b94fcaeca24
053cd225aef31f76de6b83ef906b8041b7280881
refs/heads/master
<repo_name>arthuraguiar/sampleapp<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/data/EventosRepository.kt package com.example.sampleproject.data import com.example.sampleproject.api.EventoCheckinPost import com.example.sampleproject.api.EventosApi import com.example.sampleproject.utils.safeApiCall import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import javax.inject.Inject import javax.inject.Singleton @Singleton class EventosRepository @Inject constructor(private val eventosApi: EventosApi) { suspend fun getEventos(dispatcher: CoroutineDispatcher = Dispatchers.IO) = safeApiCall(dispatcher) { eventosApi.getEventos() } suspend fun getEvento(eventoId: Int, dispatcher: CoroutineDispatcher = Dispatchers.IO) = safeApiCall(dispatcher) { eventosApi.getEvento(eventoId) } suspend fun checkInEvento( eventoCheckinPost: EventoCheckinPost, dispatcher: CoroutineDispatcher = Dispatchers.Main ) = safeApiCall(dispatcher) { eventosApi.checkInEvento(eventoCheckinPost) } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/di/AppModule.kt package com.example.sampleproject.di import com.example.sampleproject.api.EventosApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Qualifier import javax.inject.Singleton @Module @InstallIn(ApplicationComponent::class) object AppModule { @Provides @Singleton fun provideRetrofit(): Retrofit = Retrofit .Builder() .baseUrl(EventosApi.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() @Provides @Singleton fun provideEventosApi(retrofit: Retrofit): EventosApi = retrofit.create(EventosApi::class.java) @ApplicationScope @Provides @Singleton fun provideCoroutineScope() = CoroutineScope(SupervisorJob()) } @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/ui/listaeventos/ListaEventosViewModel.kt package com.example.sampleproject.ui.listaeventos import android.widget.ImageView import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.sampleproject.api.EventoResponse import com.example.sampleproject.data.EventosRepository import com.example.sampleproject.utils.Constantes.NETWORK_ERROR import com.example.sampleproject.utils.Constantes.RESQUEST_ERRO import com.example.sampleproject.utils.ResultWrapper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class ListaEventosViewModel @ViewModelInject constructor( private val eventosRepository: EventosRepository ) : ViewModel() { private val _eventos = MutableLiveData<List<EventoResponse>>() val eventos: LiveData<List<EventoResponse>> get() = _eventos private val eventoChannel = Channel<EventoTrigger>() val eventoTrigger = eventoChannel.receiveAsFlow() fun fetchEventos() { viewModelScope.launch(Dispatchers.Main) { when (val response = eventosRepository.getEventos(Dispatchers.Main)) { is ResultWrapper.NetworkError -> { eventoChannel.send(EventoTrigger.ErrorOnEventosRequest(NETWORK_ERROR)) } is ResultWrapper.GenericError -> { eventoChannel.send( EventoTrigger .ErrorOnEventosRequest("$RESQUEST_ERRO\n $response.error") ) } is ResultWrapper.Success -> { eventoChannel.send(EventoTrigger.OnEventosRequestSucess) response.value.run { _eventos.value = this } } } } } fun onEventoClicked(evento: EventoResponse, imageView: ImageView) = viewModelScope.launch { eventoChannel.send(EventoTrigger.NavigateToEventoScreen(evento, imageView)) } sealed class EventoTrigger { data class NavigateToEventoScreen(val evento: EventoResponse, val imageView: ImageView) : EventoTrigger() object OnEventosRequestSucess: EventoTrigger() data class ErrorOnEventosRequest(val errorMsg: String) : EventoTrigger() } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/SampleAppApplication.kt package com.example.sampleproject import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class SampleAppApplication: Application() { }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/utils/Constantes.kt package com.example.sampleproject.utils object Constantes { const val EVENTO = "evento" const val NETWORK_ERROR = "Erro de Conexao" const val RESQUEST_ERRO = "Ops ..." const val CHECK_IN_SUCESS = "Check In feito com sucesso!" const val EMAIL_INVALIDO = "Email informado é invalido!" }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/ui/listaeventos/ListaEventosFragment.kt package com.example.sampleproject.ui.listaeventos import android.os.Bundle import android.view.View import android.widget.ImageView import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.FragmentNavigatorExtras import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.example.sampleproject.R import com.example.sampleproject.api.EventoResponse import com.example.sampleproject.databinding.FragmentListaEventosBinding import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.android.synthetic.main.fragment_lista_eventos.* import kotlinx.coroutines.flow.collect @AndroidEntryPoint class ListaEventosFragment : Fragment(R.layout.fragment_lista_eventos), EventosAdapter.EventoOnClickListener { private val viewModel: ListaEventosViewModel by viewModels() private lateinit var binding: FragmentListaEventosBinding override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentListaEventosBinding.bind(view) val evensosAdapter = EventosAdapter(this) viewModel.fetchEventos() binding.apply { lista_eventos_recyclerview.apply { adapter = evensosAdapter layoutManager = LinearLayoutManager(requireContext()) setHasFixedSize(true) } button_retry.setOnClickListener { viewModel.fetchEventos() } } viewModel.eventos.observe(viewLifecycleOwner) { evensosAdapter.submitList(it) } viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.eventoTrigger.collect { eventTrigger -> when (eventTrigger) { is ListaEventosViewModel.EventoTrigger.OnEventosRequestSucess ->{ binding.buttonRetry.visibility = View.GONE } is ListaEventosViewModel.EventoTrigger.ErrorOnEventosRequest ->{ onRequestError(eventTrigger.errorMsg) } is ListaEventosViewModel.EventoTrigger.NavigateToEventoScreen -> { val extras = FragmentNavigatorExtras( eventTrigger.imageView to eventTrigger.evento.title ) val action = ListaEventosFragmentDirections .actionListaEventosFragmentToEventoFragment(eventTrigger.evento) findNavController().navigate(action, extras) } } } } } override fun onItemClick(evento: EventoResponse, imageView: ImageView) { viewModel.onEventoClicked(evento, imageView) } private fun onRequestError(msg: String){ binding.buttonRetry.visibility = View.VISIBLE Snackbar.make(requireView(), msg, Snackbar.LENGTH_LONG).show() } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/ui/evento/EventoViewModel.kt package com.example.sampleproject.ui.evento import androidx.hilt.Assisted import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.* import com.example.sampleproject.api.EventoCheckinPost import com.example.sampleproject.api.EventoResponse import com.example.sampleproject.data.EventosRepository import com.example.sampleproject.utils.Constantes.CHECK_IN_SUCESS import com.example.sampleproject.utils.Constantes.EMAIL_INVALIDO import com.example.sampleproject.utils.Constantes.EVENTO import com.example.sampleproject.utils.Constantes.NETWORK_ERROR import com.example.sampleproject.utils.ResultWrapper import com.example.sampleproject.utils.validateEmailFormat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch class EventoViewModel @ViewModelInject constructor( private val eventosRepository: EventosRepository, @Assisted private val state: SavedStateHandle ) : ViewModel() { val eventoArgs = state.get<EventoResponse>(EVENTO) private val _evento = MutableLiveData<EventoResponse>() val evento: LiveData<EventoResponse> get() = _evento private val eventoChannel = Channel<EventoAction>() val eventoAction = eventoChannel.receiveAsFlow() fun getEvento() { viewModelScope.launch(Dispatchers.Main) { when (val response = eventosRepository.getEvento(eventoArgs?.id ?: 0, Dispatchers.Main)) { is ResultWrapper.NetworkError -> { eventoChannel.send(EventoAction.OnFetchEventoError(NETWORK_ERROR)) } is ResultWrapper.GenericError -> { eventoChannel.send(EventoAction.OnFetchEventoError(response.error)) } is ResultWrapper.Success -> { response.value.run { _evento.value = this } } } } } fun onCheckinButtonClicked() = viewModelScope.launch { evento.value?.let {eventoResponse -> eventoChannel.send(EventoAction.InflateCheckinDialog(eventoResponse)) } } fun checkIn(nome: String, email: String) { viewModelScope.launch { if(!email.validateEmailFormat()){ eventoChannel.send(EventoAction.OnEmailInvalid(EMAIL_INVALIDO)) return@launch } val response = eventosRepository.checkInEvento( EventoCheckinPost( eventId = eventoArgs?.id ?: 0, name = nome, email = email ) ) when(response){ is ResultWrapper.NetworkError ->{ eventoChannel.send(EventoAction.OnCheckInError(NETWORK_ERROR)) } is ResultWrapper.GenericError -> { eventoChannel.send(EventoAction.OnCheckInError(response.error)) } is ResultWrapper.Success ->{ eventoChannel.send(EventoAction.OnCheckInSucess(CHECK_IN_SUCESS)) } } } } sealed class EventoAction{ data class OnFetchEventoError(val msg: String): EventoAction() data class InflateCheckinDialog(val evento:EventoResponse): EventoAction() data class OnCheckInSucess(val msg: String): EventoAction() data class OnCheckInError(val msg: String): EventoAction() data class OnEmailInvalid(val msg: String): EventoAction() } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/ui/evento/EventoFragment.kt package com.example.sampleproject.ui.evento import android.app.AlertDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.transition.TransitionInflater import com.bumptech.glide.Glide import com.example.sampleproject.R import com.example.sampleproject.api.EventoResponse import com.example.sampleproject.databinding.CheckinDialogBinding import com.example.sampleproject.databinding.FragmentEventoBinding import com.example.sampleproject.utils.formatToDate import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collect @AndroidEntryPoint class EventoFragment : Fragment(R.layout.fragment_evento) { private val viewModel: EventoViewModel by viewModels() private lateinit var binding: FragmentEventoBinding private var dialog: AlertDialog? = null private var dialogBinding: CheckinDialogBinding? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move) } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentEventoBinding.bind(view) viewModel.getEvento() viewModel.eventoArgs?.let { evento -> binding.apply { populateBinding(this, evento) } } viewModel.evento.observe(viewLifecycleOwner) { evento -> binding.apply { populateBinding(this, evento) } } binding.apply { checkInButton.setOnClickListener { viewModel.onCheckinButtonClicked() } } viewLifecycleOwner.lifecycleScope.launchWhenStarted { viewModel.eventoAction.collect { eventoAction -> when (eventoAction) { is EventoViewModel.EventoAction.OnFetchEventoError ->{ showSnackBarMsg(eventoAction.msg) } is EventoViewModel.EventoAction.InflateCheckinDialog -> { inflateFragment() } is EventoViewModel.EventoAction.OnCheckInSucess ->{ dialogBinding?.checkinLoading?.visibility = View.GONE showSnackBarMsg(eventoAction.msg) dialog?.dismiss() } is EventoViewModel.EventoAction.OnCheckInError ->{ dialogBinding?.checkinLoading?.visibility = View.GONE showSnackBarMsg(eventoAction.msg) } is EventoViewModel.EventoAction.OnEmailInvalid ->{ dialogBinding?.checkinLoading?.visibility = View.GONE showSnackBarMsg(eventoAction.msg) } } } } } private fun populateBinding( fragmentEventoBinding: FragmentEventoBinding, evento: EventoResponse ) { fragmentEventoBinding.dataEventoTextview.text = evento.date.formatToDate() fragmentEventoBinding.eventoResumoTextview.text = evento.description fragmentEventoBinding.eventoTitleTextview.text = evento.title fragmentEventoBinding.imageview.apply { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { this.transitionName = evento.title } Glide.with(this) .load(evento.image) .error(R.drawable.ic_baseline_error_24) .into(this) } } private fun inflateFragment(){ dialogBinding = CheckinDialogBinding.inflate(LayoutInflater.from(context)) val builder = AlertDialog.Builder(context) builder.setView(dialogBinding?.root) dialogBinding?.apply { checkinButton.setOnClickListener { checkinLoading.visibility = View.VISIBLE viewModel.checkIn( nomeEditTextInput.text.toString(), emailEditTextInput.text.toString() ) } cancelCheckinButton.setOnClickListener { dialog?.dismiss() dialog = null } } dialog = builder.create() dialog?.show() } private fun showSnackBarMsg(msg:String){ Snackbar.make(requireView(), msg, Snackbar.LENGTH_LONG).show() } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/api/EventosApi.kt package com.example.sampleproject.api import com.google.gson.JsonObject import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Path interface EventosApi { @GET("events/") suspend fun getEventos(): List<EventoResponse> @GET("events/{id}") suspend fun getEvento(@Path("id") eventoId: Int): EventoResponse @POST("checkin") suspend fun checkInEvento(@Body eventoCheckinPost: EventoCheckinPost):JsonObject companion object { const val BASE_URL = "https://5f5a8f24d44d640016169133.mockapi.io/api/" } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/utils/Extensions.kt package com.example.sampleproject.utils import android.text.TextUtils import java.text.SimpleDateFormat import java.util.* fun Long.formatToDate():String{ val formatter = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()) val calendar = Calendar.getInstance() calendar.timeInMillis = this return formatter.format(calendar.time) } fun String.validateEmailFormat():Boolean{ return if (TextUtils.isEmpty(this)) { false; } else { android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches(); } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/api/EventoResponse.kt package com.example.sampleproject.api import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.math.BigDecimal @Parcelize data class EventoResponse( val people: List<Pessoa>, val date: Long, val description: String, val image: String, /*Longitude e Latitude mantidos como String pois servem apenas para visualizacao*/ val longitude: String, val latitude: String, val price: BigDecimal, val title: String, val id: Int ):Parcelable data class EventoCheckinPost( val eventId: Int, val name: String, val email: String ) <file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/ui/listaeventos/EventosAdapter.kt package com.example.sampleproject.ui.listaeventos import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions import com.bumptech.glide.request.RequestOptions import com.example.sampleproject.R import com.example.sampleproject.api.EventoResponse import com.example.sampleproject.databinding.ItemEventoBinding import com.example.sampleproject.utils.formatToDate class EventosAdapter(val eventoOnClickListener: EventoOnClickListener) : ListAdapter<EventoResponse, EventosAdapter.EventosViewHolder>(DiffCallback()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventosViewHolder { return EventosViewHolder( ItemEventoBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun onBindViewHolder(holder: EventosViewHolder, position: Int) = holder.bind(getItem(position)) inner class EventosViewHolder(private val binding: ItemEventoBinding) : RecyclerView.ViewHolder(binding.root) { init { binding.apply { root.setOnClickListener { val position = adapterPosition if (position != RecyclerView.NO_POSITION) { eventoOnClickListener.onItemClick(getItem(position), this.imageView) } } } } fun bind(evento: EventoResponse) { binding.apply { textViewTitle.text = evento.title textViewPrice.text = String.format("R$ %.2f", evento.price) textViewDate.text = evento.date.formatToDate() imageView.apply { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { transitionName = evento.title } Glide.with(itemView) .load(evento.image) .error(R.drawable.ic_baseline_error_24) .into(this) } } } } class DiffCallback() : DiffUtil.ItemCallback<EventoResponse>() { override fun areItemsTheSame(oldItem: EventoResponse, newItem: EventoResponse) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: EventoResponse, newItem: EventoResponse) = oldItem == newItem } interface EventoOnClickListener { fun onItemClick(evento: EventoResponse, imageView: ImageView) } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/utils/NetworkHelperUtil.kt package com.example.sampleproject.utils import retrofit2.HttpException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import java.io.IOException sealed class ResultWrapper<out T> { data class Success<out T>(val value: T): ResultWrapper<T>() data class GenericError(val code: Int? = null, val error: String): ResultWrapper<Nothing>() object NetworkError: ResultWrapper<Nothing>() } suspend fun <T> safeApiCall(dispatcher: CoroutineDispatcher, apiCall: suspend () -> T): ResultWrapper<T> { return withContext(dispatcher) { try { ResultWrapper.Success(apiCall.invoke()) } catch (throwable: Throwable) { when (throwable) { is IOException -> ResultWrapper.NetworkError is HttpException -> { val code = throwable.code() val errorResponse = throwable.message() ResultWrapper.GenericError(code, errorResponse) } else -> { ResultWrapper.GenericError(null, "") } } } } }<file_sep>/sampleproject/app/src/main/java/com/example/sampleproject/api/Pessoa.kt package com.example.sampleproject.api import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Pessoa( private val nome: String ): Parcelable
5d3d41b6997b91f6532f1be6a425e207db3f365b
[ "Kotlin" ]
14
Kotlin
arthuraguiar/sampleapp
fb2f42ca2a919c9c16198831cdce7905b5383ea8
91f82b541cbee20efe8b1292a87fc92455d5e9db
refs/heads/master
<repo_name>abhayrobotics/Pokemon-Game<file_sep>/main.py import pygame import sys import random import math from pygame import mixer import time # initialse the pygame pygame.init() # TITLE AND LOGO pygame.display.set_caption("Pokemon") icon = pygame.image.load('sprites/icon.png') pygame.display.set_icon(icon) # Global variables SCREENWIDTH = 850 SCREENHEIGHT = 520 GROUNDY = 0.87 * SCREENHEIGHT CHARACTER_IN_CONTROL = "player" # default case # create the Screen screen = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) # Background backgroundImg = pygame.image.load('sprites/background2.png') # trees treeX_change = 0 tree1 = pygame.image.load('sprites/tree1.png') tree2 = pygame.image.load('sprites/tree2.png') tree3 = pygame.image.load('sprites/tree3.png') # tree4 = pygame.image.load('sprites/tree4.png') tree5 = pygame.image.load('sprites/tree5.png') all_trees = [tree1, tree2, tree3, tree5] tree_list = [] treeX = [400, 400 + random.randint(150, 400), 800 + random.randint(150, 400)] # Player playerImg = pygame.image.load('sprites/player.png') playerX = 100 playerY = GROUNDY - playerImg.get_height() playerY_min = GROUNDY - playerImg.get_height() playerX_change = 0 playerY_change = 0 playerY_max = GROUNDY - playerImg.get_height() - 130 player_jumping_status = False player_jumping_dir = 0 # pokeball pokeballImg = pygame.image.load('sprites/pokeball.png') pokeballX = 100 pokeballY = GROUNDY - pokeballImg.get_height() - 100 pokeballX_change = 0 pokeballY_change = 0 pokeball_status = "ready" # POKEMON bulbasaurImg = pygame.image.load('sprites/bulbasaur.png') bulbasaurX = 200 bulbasaurY = GROUNDY - bulbasaurImg.get_height() bulbasaurY_min = GROUNDY - bulbasaurImg.get_height() bulbasaurY_change = 0 bulbasaurY_max = GROUNDY - bulbasaurImg.get_height() - 100 bulbasaur_jumping_status = False bulbasaur_jumping_dir = 0 # Boss enemy squirtelV3Img = pygame.image.load('sprites/squirtelV3.png') squirtelV3X = 600 squirtelV3Y = GROUNDY - squirtelV3Img.get_height() class Jump(): # this class provides jumping technique to any character GROUNDY = 0.87 * SCREENHEIGHT def __init__(self, characterImg, characterX, characterY, characterY_change, characterY_max, jumping_status, jumping_dir): self.characterImg = characterImg self.characterX = characterX self.characterY_change = characterY_change self.characterY = characterY self.characterY_max = characterY_max self.jumping_status = jumping_status self.jumping_dir = jumping_dir def jumpTechnique(self): # print("class ", self.jumping_status) self.characterY_change = 0 # print(self.characterY, self.characterY_max) if self.jumping_status: if (GROUNDY - self.characterImg.get_height() + 15 >= self.characterY >= self.characterY_max) \ and self.jumping_dir == "up": # 15 px above is safety factor( must not be removed) # print("up") self.characterY_change = -5 if self.characterY <= self.characterY_max and self.jumping_dir == "up": # print("direction change") self.jumping_dir = "down" self.characterY_change = +5 if (GROUNDY - self.characterImg.get_height() >= self.characterY >= self.characterY_max) \ and self.jumping_dir == "down": # print("down") self.characterY_change = +5 if self.characterY > GROUNDY - self.characterImg.get_height() and self.jumping_dir == "down": self.characterY_change = 0 self.characterY = GROUNDY - self.characterImg.get_height() # reset self.characterY position self.jumping_status = False return self.characterY_change, self.jumping_dir, self.jumping_status # Blitting Functions def player(x, y): screen.blit(playerImg, (playerX, playerY)) def pokeball(x, y): screen.blit(pokeballImg, (x, y)) def bulbasaur(x, y): screen.blit(bulbasaurImg, (x, y)) def squirtelV3(x, y): screen.blit(squirtelV3Img, (x, y)) def tree_blit(chosen_tree, x, y): # blit a tree screen.blit(chosen_tree, (x, y)) # logical Functions def randomtree(): # choose a random tree return random.choice(all_trees) if __name__ == '__main__': # Generate 3 random Trees no_of_trees = 1 while no_of_trees <= 3: tree_list.append(randomtree()) no_of_trees += 1 running = True # main loop while running: # print(running) # RGB value screen.fill((0, 0, 0)) # background img screen.blit(backgroundImg, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): running = False pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: treeX_change = -2 print("Right") if event.key == pygame.K_LEFT: treeX_change = +2 print("Left") if event.key == pygame.K_b and player_jumping_status == False: CHARACTER_IN_CONTROL = "bulbasaur" if event.key == pygame.K_p and bulbasaur_jumping_status == False: CHARACTER_IN_CONTROL = "player" if event.key == pygame.K_SPACE: # SHOOT event depending on CHARACTER_IN_CONTROL if CHARACTER_IN_CONTROL == "player": pokeballX = playerX + 30 pokeballY = playerY + 30 pokeballX_change = 6 print("Player Shoot") pokeball_status = "fire" if CHARACTER_IN_CONTROL == "bulbasaur": pass if event.key == pygame.K_UP: # Jump event depending on CHARACTER_IN_CONTROL # Jumping event player if bulbasaur_jumping_status == False and CHARACTER_IN_CONTROL == "player": print("Player JUMP") player_jumping_status = True # print(f"jumping_status is{jumping_status}") player_jumping_dir = "up" # Jumping event Bulbasaur if player_jumping_status == False and CHARACTER_IN_CONTROL == "bulbasaur": print("Bulbasaur JUMP") bulbasaur_jumping_status = True # print(f"jumping_status is{jumping_status}") bulbasaur_jumping_dir = "up" if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: # tree will move only when player moves treeX_change = 0 if event.key == pygame.K_LEFT: # tree will move only when player moves treeX_change = 0 # tree generator # incrementing x coordinate and then using x to put in randam tree generator # ( random in choosing tree + random in distance between tree) two list simultaneously --zip for tree_X_coordinate, k in zip(treeX, tree_list): a = treeX.index(tree_X_coordinate) # finding index a # print(a) tree_X_coordinate += treeX_change treeX[a] = tree_X_coordinate # changing the incremented x # print(k, tree_X_coordinate, 200) tree_blit(k, tree_X_coordinate, 200) # if tree exists from window , spawning new random tree if treeX[0] + tree_list[0].get_width() < -200: # swapping tree and x position ( deleting tree with index 0 and adding a new tree) treeX[0], treeX[1] = treeX[1], treeX[2] tree_list[0], tree_list[1] = tree_list[1], tree_list[2] tree_list[2] = randomtree() treeX[2] = 900 + random.randint(100, 400) # player jump if CHARACTER_IN_CONTROL == "player": player_jump = Jump(playerImg, playerX, playerY, playerY_change, playerY_max, player_jumping_status, player_jumping_dir) playerY_change, player_jumping_dir, player_jumping_status = player_jump.jumpTechnique() # bulbasaur jump if CHARACTER_IN_CONTROL == "bulbasaur": bulbasaur_jump = Jump(bulbasaurImg, bulbasaurX, bulbasaurY, bulbasaurY_change, bulbasaurY_max, bulbasaur_jumping_status, bulbasaur_jumping_dir) bulbasaurY_change, bulbasaur_jumping_dir, bulbasaur_jumping_status = bulbasaur_jump.jumpTechnique() # blitting pokeball when shoot if pokeball_status == "fire": # print(pokeballX,pokeballY) screen.blit(pokeballImg, (pokeballX, pokeballY)) # player Movement playerY += playerY_change player(playerX, playerY) # bulbasaur Movement bulbasaurY += bulbasaurY_change # bulbasaur(bulbasaurX, bulbasaurY) # pokeball Movement pokeballX += pokeballX_change # enemy squirtelV3(squirtelV3X, squirtelV3Y) pygame.display.update() <file_sep>/README.md # Pokemon-Game Pokemon Game using Python (Game is under process) ![Preview Not Available](preview1.png) ![Preview Not Available](preview2.png) ![Preview Not Available](preview3.png) ![Preview Not Available](preview4.png)
42a3ad6750ab3fe9397a6d789f8174b9c8ebb78d
[ "Markdown", "Python" ]
2
Python
abhayrobotics/Pokemon-Game
2c57b26022db36b647a84b40a7783da26e0b85da
87b60d562263bc87a22845c805c643a7300a20eb
refs/heads/master
<file_sep>require "spec_helper" describe Nfe do it "has a version number" do expect(Nfe::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end <file_sep># encoding: UTF-8 require 'nokogiri' require 'roxml' require 'json' module NFe class NFeProc include ROXML xml_name :NFeProc xml_accessor :xmlns, :from => "http://www.portalfiscal.inf.br/nfe" # attribute with name 'ISBN' #xmlns="http://www.portalfiscal.inf.br/nfe" # xml_accessor :title # xml_accessor :description, :cdata => true # text node with cdata protection # xml_accessor :author end class EntidadeNFe include ROXML @@validations = [] class << self alias :nfe_attr :xml_accessor def xml_accessor(*attrs) attr_accessor *attrs # super(*attrs) end def nfe_attrs roxml_attrs.map(&attr_name) end end def nfe_attributes self.class.nfe_attrs end def to_nfe_xml(file) #entidade = EntidadeNFe.from_xml(File.read(File.expand_path('example-user.xml', File.dirname(__FILE__)))) #entidade = NFe::EntidadeNFe.from_xml(File.read(File.expand_path(file, File.dirname(__FILE__)))) entidade = Nokogiri::XML(File.open(file)) doc = Nokogiri::XML::Document.new doc.root = self.to_xml # open("entidade_nfe.xml", 'w') do |file| # file << doc.serialize # end puts ">>>>>> #{doc.root.to_s}" end def to_nfe #depois fazer o teste com REXML doc = Nokogiri::XML::Document.new doc.root = to_xml doc.serialize end # def to_s # self.respond_to? :to_nfe ? to_nfe : super # end def serialize(params) params.each do |key, value| send("#{key}=", value) if respond_to?(key) end end def xml_to_hash(xml) hash = {} xml.children.each do |i| hash.store(i.name, i.text) end hash end def to_xml(xml) hash = '' xml.children.each do |i| hash << "<#{i.name}>#{i.text}</#{i.name}>" end hash end end end <file_sep># encoding: UTF-8 module NFe class NotaFiscal < NFe::EntidadeNFe xml_name :infNFe attr_accessor :ide attr_accessor :emit attr_accessor :dest attr_accessor :prod attr_accessor :icms_tot attr_accessor :transp attr_accessor :veiculo attr_accessor :vol attr_accessor :info attr_accessor :infoProt def initializer #@versao_processo_emissao = Nfe::Config::Params::VERSAO_PADRAO @ide = NFe::IdentificacaoNFe.new @emit = NFe::Emitente.new @emit.endereco_emitente = NFe::EnderecoEmitente.new @dest = NFe::Destinatario.new @dest.endereco_destinatario = NFe::EnderecoDesinatario.new @prod = [] @icms_tot = NFe::IcmsTot.new @transp = NFe::Transportadora.new @veiculo = NFe::Veiculo.new @vol = NFe::Volume.new @info = NFe::Info.new @infoProt = NFe::InfoProtocolo.new @versao = '2.0' #criar uma constante em params da versao da NF-e end def load_xml_serealize(file) doc = Nokogiri::XML(File.open(file)) self.ide = NFe::IdentificacaoNFe.new self.emit = NFe::Emitente.new self.dest = NFe::Destinatario.new self.emit.endereco_emitente = NFe::EnderecoEmitente.new self.icms_tot = NFe::IcmsTot.new self.transp = NFe::Transportadora.new self.veiculo = NFe::Veiculo.new self.vol = NFe::Volume.new self.info = NFe::Info.new self.infoProt = NFe::InfoProtocolo.new produto = Produto.new produto.xml_to_hash(file) self.ide.serialize(@ide.xml_to_hash(doc.elements.css('ide'))) self.emit.serialize(@emit.xml_to_hash(doc.elements.css('emit'))) self.emit.endereco_emitente = NFe::EnderecoEmitente.new.xml_to_hash(doc.elements.css('emit')) self.dest.serialize(@dest.xml_to_hash(doc.elements.css('dest'))) self.dest.endereco_destinatario = NFe::EnderecoDestinatario.new.xml_to_hash(doc.elements.css('dest')) self.icms_tot.serialize(@icms_tot.xml_to_hash(doc.elements.css('total/ICMSTot'))) self.transp.serialize(@transp.xml_to_hash(doc.elements.css('transp/transporta'))) self.veiculo.serialize(@veiculo.xml_to_hash(doc.elements.css('transp/veicTransp'))) self.vol.serialize(@vol.xml_to_hash(doc.elements.css('transp/vol'))) self.info.serialize(@info.xml_to_hash(doc.elements.css('infAdic'))) self.infoProt.serialize(@infoProt.xml_to_hash(doc.elements.css('protNFe/infProt'))) self.prod = produto.all_products self end end end<file_sep># encoding: UTF-8 module NFe class Veiculo < NFe::EntidadeNFe xml_name :veicTransp attr_accessor :placa attr_accessor :UF # attr_accessor :RNTC # "RNTC" => RCNT # "RNTC" => params["RNTC"] def attributes @attributes = { "placa" => placa, "UF" => UF } end def attributes=(params) @attributes = { "placa" => params["placa"], "UF" => params["UF"] } end end end<file_sep># encoding: UTF-8 module NFe class IcmsTot < NFe::EntidadeNFe attr_accessor :vBC attr_accessor :vICMS attr_accessor :vICMSDeson attr_accessor :vFCPUFDest attr_accessor :vICMSUFDest attr_accessor :vICMSUFRemet attr_accessor :vBCST attr_accessor :vST attr_accessor :vProd attr_accessor :vFrete attr_accessor :vSeg attr_accessor :vDesc attr_accessor :vII attr_accessor :vIPI attr_accessor :vPIS attr_accessor :vCOFINS attr_accessor :vOutro attr_accessor :vNF attr_accessor :vTotTrib def initialize(attrs = {}) self.vBC = attrs[:vBC] self.vICMS = attrs[:vICMS] self.vICMSDeson = attrs[:vICMSDeson] self.vFCPUFDest = attrs[:vFCPUFDest] self.vICMSUFDest = attrs[:vICMSUFDest] self.vICMSUFRemet = attrs[:vICMSUFRemet] self.vBCST = attrs[:vBCST] self.vST = attrs[:vST] self.vProd = attrs[:vProd] self.vFrete = attrs[:vFrete] self.vSeg = attrs[:vSeg] self.vDesc = attrs[:vDesc] self.vII = attrs[:vII] self.vIPI = attrs[:vIPI] self.vPIS = attrs[:vPIS] self.vCOFINS = attrs[:vCOFINS] self.vOutro = attrs[:vOutro] self.vNF = attrs[:vNF] self.vTotTrib = attrs[:vTotTrib] end def attributes @attributes = { "vBC" => vBC, "vICMS" => vICMS, "vICMSDeson" => vICMSDeson, "vFCPUFDest" => vFCPUFDest, "vICMSUFDest" => vICMSUFDest, "vICMSUFRemet" => vICMSUFRemet, "vBCST" => vBCST, "vST" => vST, "vProd" => vProd, "vFrete" => vFrete, "vSeg" => vSeg, "vDesc" => vDesc, "vII" => vII, "vIPI" => vIPI, "vPIS" => vPIS, "vCOFINS" => vCOFINS, "vOutro" => vOutro, "vNF" => vNF, "vTotTrib" => vTotTrib } end def attributes=(params) self.vBC = params['vBC'], self.vICMS = params['vICMS'], self.vICMSDeson = params['vICMSDeson'], self.vFCPUFDest = params['vFCPUFDest'], self.vICMSUFDest = params['vICMSUFDest'], self.vICMSUFRemet = params['vICMSUFRemet'], self.vBCST = params['vBCST'], self.vST = params['vST'], self.vProd = params['vProd'], self.vFrete = params['vFrete'], self.vSeg = params['vSeg'], self.vDesc = params['vDesc'], self.vII = params['vII'], self.vIPI = params['vIPI'], self.vPIS = params['vPIS'], self.vCOFINS = params['vCOFINS'], self.vOutro = params['vOutro'], self.vNF = params['vNF'], self.vTotTrib = params['vTotTrib'] end # def xml_to_hash(xml) #node XML # xml.children.css('enderDest').each do |p| # self.vBC = p.css('vBC').text # self.vICMS = p.css('vICMS').text # self.vICMSDeson = p.css('vICMSDeson').text # self.vFCPUFDest = p.css('vFCPUFDest').text # self.vICMSUFDest = p.css('vICMSUFDest').text # self.vICMSUFRemet = p.css('vICMSUFRemet').text # self.vBCST = p.css('vBCST').text # self.vST = p.css('vST').text # self.vProd = p.css('vProd').text # self.vFrete = p.css('vFrete').text # self.vSeg = p.css('vSeg').text # self.vDesc = p.css('vDesc').text # self.vII = p.css('vII').text # self.vIPI = p.css('vIPI').text # self.vPIS = p.css('vPIS').text # self.vCOFINS = p.css('vCOFINS').text # self.vOutro = p.css('vOutro').text # self.vNF = p.css('vNF').text # self.vTotTrib = p.css('vTotTrib').text # end # self # end end end <file_sep># encoding: UTF-8 module NFe class InfoProtocolo < NFe::EntidadeNFe xml_name :infProt attr_accessor :tpAmb attr_accessor :verAplic attr_accessor :chNFe attr_accessor :dhRecbto attr_accessor :nProt attr_accessor :digVal attr_accessor :cStat attr_accessor :xMotivo def attributes @attributes = { "tpAmb" => tpAmb, "verAplic" => verAplic, "chNFe" => chNFe, "dhRecbto" => dhRecbto, "nProt" => nProt, "cStat" => cStat, "xMotivo" => xMotivo } end def attributes=(params) @attributes = { "tpAmb" => params["tpAmb"], "verAplic" => params["verAplic"], "chNFe" => params["chNFe"], "dhRecbto" => params["dhRecbto"], "nProt" => params["nProt"], "cStat" => params["cStat"], "xMotivo" => params["xMotivo"] } end end end<file_sep># encoding: UTF-8 module NFe class Emitente < NFe::EntidadeNFe attr_accessor :CNPJ attr_accessor :xNome attr_accessor :enderEmit attr_accessor :IE attr_accessor :IM attr_accessor :CNAE attr_accessor :CRT attr_accessor :endereco_emitente def initializer self.endereco_emitente = NFe::EnderecoEmitente.new end def attributes @attributes = { "CNPJ" => CNPJ, "xNome" => xNome, "enderEmit" => enderEmit, "IE" => IE, "IM" => IM, "CNAE" => CNAE, "CRT" => CRT, } #@endereco_emitente = @endereco_emitente.serealize(enderEmit) end def attributes=(params) @attributes = { "CNPJ" => params["CNPJ"], "xNome" => params["xNome"], "enderEmit" => params["enderEmit"], "IE" => params["IE"], "IM" => params["IM"], "CNAE" => params["CNAE"], "CRT" => params["CRT"] } end end end<file_sep># encoding: UTF-8 module NFe class Info < NFe::EntidadeNFe xml_name :infAdic attr_accessor :infCpl def attributes @attributes = { "infCpl" => infCpl } end def attributes=(params) @attributes = { "infCpl" => params["infCpl"] } end end end<file_sep># encoding: UTF-8 module NFe class IdentificacaoNFe < NFe::EntidadeNFe xml_name :ide attr_accessor :cUF attr_accessor :cNF attr_accessor :natOp attr_accessor :indPag attr_accessor :mod attr_accessor :serie attr_accessor :nNF attr_accessor :dhEmi attr_accessor :dSaiEnt #attr_accessor :hSaiEnt attr_accessor :tpNF attr_accessor :idDest attr_accessor :cMunFG attr_accessor :tpImp attr_accessor :tpEmis attr_accessor :cDV attr_accessor :tpAmb attr_accessor :finNFe attr_accessor :indFinal attr_accessor :indPres attr_accessor :procEmi attr_accessor :verProc attr_accessor :dhCont attr_accessor :xJust def attributes @attributes = { "cUF" => cUF, "cNF" => cNF, "natOp" => natOp, "indPag" => indPag, "mod" => mod, "serie" => serie, "nNF" => nNF, "dhEmi" => dhEmi, "dSaiEnt" => dSaiEnt, "tpNF" => tpNF, "idDest" => idDest, "cMunFG" => cMunFG, "tpImp" => tpImp, "tpEmis" => tpEmis, "cDV" => cDV, "tpAmb" => tpAmb, "finNFe" => finNFe, "indFinal" => indFinal, "indPres" => indPres, "procEmi" => procEmi, "verProc" => verProc } end def attributes=(params) @attributes = { "cUF" => params["cUF"], "cNF" => params["cNF"], "natOp" => params["natOp"], "indPag" => params["indPag"], "mod" => params["mod"], "serie" => params["serie"], "nNF" => params["nNF"], "dhEmi" => params["dhEmi"], "dSaiEnt" => params["dSaiEnt"], "tpNF" => params["tpNF"], "idDest" => params["idDest"], "cMunFG" => params["cMunFG"], "tpImp" => params["tpImp"], "tpEmis" => params["tpEmis"], "cDV" => params["cDV"], "tpAmb" => params["tpAmb"], "finNFe" => params["finNFe"], "indFinal" => params["indFinal"], "indPres" => params["indPres"], "procEmi" => params["procEmi"], "verProc" => params["verProc"] } end end end<file_sep># encoding: UTF-8 module NFe class Transportadora < NFe::EntidadeNFe xml_name :transporta attr_accessor :CNPJ attr_accessor :xNome attr_accessor :IE attr_accessor :xEnder attr_accessor :xMun attr_accessor :UF def attributes @attributes = { "CNPJ" => CNPJ, "xNome" => xNome, "IE" => IE, "xEnder" => xEnder, "xMun" => xMun, "UF" => UF } end def attributes=(params) @attributes = { "CNPJ" => params["CNPJ"], "xNome" => params["xNome"], "IE" => params["IE"], "xEnder" => params["xEnder"], "xMun" => params["xMun"], "UF" => params["UF"] } end end end<file_sep># encoding: UTF-8 class Imposto #/imposto/ICMS/ICMS00 attr_accessor :cProd attr_accessor :cEAN attr_accessor :xProd attr_accessor :NCM attr_accessor :EXTIPI attr_accessor :CFOP attr_accessor :uCom attr_accessor :qCom end<file_sep># encoding: UTF-8 module NFe class EnderecoDestinatario < NFe::EntidadeNFe xml_name :enderEmit attr_accessor :xLgr attr_accessor :nro attr_accessor :xCpl attr_accessor :xBairro attr_accessor :cMun attr_accessor :xMun attr_accessor :UF attr_accessor :CEP attr_accessor :cPais attr_accessor :xPais attr_accessor :fone def initialize(attrs = {}) self.xLgr = attrs[:xLgr] self.nro = attrs[:nro] self.xCpl = attrs[:xCpl] self.xBairro = attrs[:xBairro] self.cMun = attrs[:cMun] self.xMun = attrs[:xMun] self.UF = attrs[:UF] self.CEP = attrs[:CEP] self.cPais = attrs[:cPais] self.xPais = attrs[:xPais] self.fone = attrs[:fone] end def attributes @attributes = { "xLgr" => xLgr, "nro" => nro, "xCpl" => xCpl, "xBairro" => xBairro, "cMun" => cMun, "xMun" => xMun, "UF" => UF, "CEP" => CEP, "cPais" => cPais, "xPais" => xPais, "fone" => fone } end def attributes=(params) self.xLgr = params[:xLgr], self.nro = params[:nro], self.xCpl = params[:xCpl], self.xBairro = params[:xBairro], self.cMun = params[:cMun], self.xMun = params[:xMun], self.UF = params[:UF], self.CEP = params[:CEP], self.cPais = params[:cPais], self.xPais = params[:xPais], self.fone = params[:fone] end def xml_to_hash(xml) #node XML xml.children.css('enderDest').each do |p| self.xLgr = p.css('xLgr').text self.nro = p.css('nro').text self.xCpl = p.css('xCpl').text self.xBairro = p.css('xBairro').text self.cMun = p.css('cMun').text self.xMun = p.css('xMun').text self.UF = p.css('UF').text self.CEP = p.css('CEP').text self.cPais = p.css('cPais').text self.xPais = p.css('xPais').text self.fone = p.css('fone').text end self end end end <file_sep># encoding: UTF-8 module NFe class Volume < NFe::EntidadeNFe xml_name :vol attr_accessor :qVol attr_accessor :esp attr_accessor :pesoL attr_accessor :pesoB def attributes @attributes = { "qVol" => qVol, "esp" => esp, "pesoL" => pesoL, "pesoB" => pesoB } end def attributes=(params) @attributes = { "qVol" => params["qVol"], "esp" => params["esp"], "pesoL" => params["pesoL"], "pesoB" => params["pesoB"] } end end end<file_sep># encoding: UTF-8 module NFe class Destinatario < NFe::EntidadeNFe xml_name :emit attr_accessor :xNome attr_accessor :CPF attr_accessor :CNPJ attr_accessor :enderDest attr_accessor :indIEDest attr_accessor :IE attr_accessor :endereco_destinatario def initializer self.endereco_destinatario = NFe::EnderecoDestinatario.new end def attributes @attributes = { "xNome" => xNome, "CPF" => CPF, "CNPJ" => CNPJ, "enderEmit" => @enderEmit, "indIEDest" => indIEDest, "IE" => IE } end def attributes=(params) @attributes = { "xNome" => params["razao_social"], "CPF" => params["cpf"], "CNPJ" => params["cnpj"], "enderDest" => params["enderDest"], "indIEDest" => params["indIEDest"], "IE" => params["IE"], } end end end <file_sep># encoding: UTF-8 #module NFe class Produto attr_accessor :cProd attr_accessor :cEAN attr_accessor :xProd attr_accessor :NCM attr_accessor :EXTIPI attr_accessor :CFOP attr_accessor :uCom attr_accessor :qCom attr_accessor :vUnCom attr_accessor :vProd attr_accessor :cEANTrib attr_accessor :uTrib attr_accessor :qTrib attr_accessor :vUnTrib attr_accessor :indTot attr_accessor :xPed attr_accessor :xPed attr_accessor :all_products def initialize(attrs = {}) self.cProd = attrs[:cProd] self.cEAN = attrs[:cEAN] self.xProd = attrs[:xProd] self.NCM = attrs[:NCM] self.EXTIPI = attrs[:EXTIPI] self.CFOP = attrs[:CFOP] self.uCom = attrs[:uCom] self.qCom = attrs[:qCom] self.vUnCom = attrs[:vUnCom] self.vProd = attrs[:vProd] self.cEANTrib = attrs[:cEANTrib] self.uTrib = attrs[:uTrib] self.qTrib = attrs[:qTrib] self.vUnTrib = attrs[:vUnTrib] self.indTot = attrs[:indTot] self.xPed = attrs[:xPed] self.all_products = [] end def attributes { "cProd" => cProd, "cEAN" => cEAN, "xProd" => xProd, "NCM" => NCM, "EXTIPI" => EXTIPI, "CFOP" => CFOP, "uCom" => uCom, "qCom" => qCom, "vUnCom" => vUnCom, "vProd" => vProd, "cEANTrib" => cEANTrib, "uTrib" => uTrib, "qTrib" => qTrib, "vUnTrib" => vUnTrib, "indTot" => indTot, "xPed" => xPed } end def attributes=(params) self.cProd = params["cProd"] self.cEAN = params["cEAN"] self.xProd = params["xProd"] self.NCM = params["NCM"] self.EXTIPI = params["EXTIPI"] self.CFOP = params["CFOP"] self.uCom = params["uCom"] self.qCom = params["qCom"] self.vUnCom = params["vUnCom"] self.vProd = params["vProd"] self.cEANTrib = params["cEANTrib"] self.uTrib = params["uTrib"] self.qTrib = params["qTrib"] self.vUnTrib = params["vUnTrib"] self.indTot = params["indTot"] self.xPed = params["xPed"] end def xml_to_hash(xml) #file xml doc = Nokogiri::XML(File.open(xml)) prods = doc.elements.css('prod').map do |p| { 'cProd' => p.css('cProd').text, 'cEAN' => p.css('cEAN').text, 'xProd' => p.css('xProd').text, 'NCM' => p.css('NCM').text, 'EXTIPI' => p.css('EXTIPI').text, 'CFOP' => p.css('CFOP').text, 'uCom' => p.css('uCom').text, 'qCom' => p.css('qCom').text, 'vUnCom' => p.css('vUnCom').text, 'vProd' => p.css('vProd').text, 'cEANTrib' => p.css('cEANTrib').text, 'uTrib' => p.css('uTrib').text, 'qTrib' => p.css('qTrib').text, 'vUnTrib' => p.css('vUnTrib').text, 'indTot' => p.css('indTot').text, 'xPed' => p.css('xPed').text } end prods.each {|p| self.all_products.push(p) } end end<file_sep>lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "nfe/version" require 'nfe/entidades/entidade_nfe.rb' require 'nfe/entidades/infNFe/nota_fiscal.rb' require 'nfe/entidades/infNFe/ide/identificacao_nfe.rb' require 'nfe/entidades/infNFe/emit/emitente.rb' require 'nfe/entidades/infNFe/emit/endereco_emitente.rb' require 'nfe/entidades/infNFe/dest/destinatario.rb' require 'nfe/entidades/infNFe/dest/endereco_destinatario.rb' require 'nfe/entidades/infNFe/det/produto.rb' require 'nfe/entidades/infNFe/det/imposto.rb' require 'nfe/entidades/infNFe/total/icmstot.rb' require 'nfe/entidades/infNFe/transp/transportadora.rb' require 'nfe/entidades/infNFe/transp/veiculo.rb' require 'nfe/entidades/infNFe/transp/volume.rb' require 'nfe/entidades/infNFe/infAdic/info.rb' require 'nfe/entidades/protNFe/infProt.rb'
53da71b8a06419bd3b114c0dee12401496fe8975
[ "Ruby" ]
16
Ruby
igorcb/ruby-nfe
a01d483395faf905a6f5721675910a0ab9feda3e
ec3c9b3a1304f427bc6799e6d15f22a06e3090f8
refs/heads/master
<file_sep># CMake 最低版本号要求 cmake_minimum_required(VERSION 3.9) # 指定运行此配置文件所需的 CMake 的最低版本; # 项目信息 project(ImageRegistration) # project:参数值是 ImageRegistration,该命令表示项目的名称是 ImageRegistration 。 # opencv的配置 find_package(OpenCV REQUIRED) message(STATUS "OpenCV library status:") message(STATUS " version: ${OpenCV_VERSION}") message(STATUS " libraries: ${OpenCV_LIBS}") message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}") include_directories(${OpenCV_INCLUDE_DIRS}) set(CMAKE_CXX_STANDARD 11) # 指定生成目标 add_executable(ImageRegistration main.cpp StarImageRegistBuilder.h StarImage.h StarImagePart.h StarImage.cpp StarImagePart.cpp StarImageRegistBuilder.cpp Util.h Util.cpp) # 将名为 main.cpp 的源文件编译成一个名称为 ImageRegistration 的可执行文件。 # 让 ImageRegistration 可以执行的文件去连接OpenCV的动态库 target_link_libraries(ImageRegistration ${OpenCV_LIBS})<file_sep>// // Created by 许舰 on 2018/1/10. // #ifndef IMAGEREGISTRATION_STARIMAGEREGISTBUILDER_H #define IMAGEREGISTRATION_STARIMAGEREGISTBUILDER_H #endif //IMAGEREGISTRATION_STARIMAGEREGISTBUILDER_H #include <iostream> #include <opencv/cv.hpp> #include "StarImage.h" #include "opencv2/xfeatures2d.hpp" #include <map> using namespace cv; using namespace std; using namespace cv::xfeatures2d; class StarImageRegistBuilder { public: static const int MERGE_MODE_MEAN = 1; static const int MERGE_MODE_MEDIAN = 2; private: StarImage targetStarImage; // 用于作为配准基准的图像信息 std::vector<StarImage> sourceStarImages; // 用于配准的图像信息 Mat_<Vec3b> targetImage; std::vector<Mat_<Vec3b>> sourceImages; Mat skyMaskMat; // 天空部分的模板 int skyBoundaryRange; // 用于去除边界部分的特征点,设置为整幅图像的5%。靠近边缘5%的天空特征点忽略不计。 int rowParts; int columnParts; // 期望图像将被划分为 rowParts * columnParts 部分 int imageCount; public: StarImageRegistBuilder(Mat_<Vec3b>& targetImage, std::vector<Mat_<Vec3b>>& sourceImages, Mat& skyMaskMat, int rowParts, int columnParts); void addSourceImagePath(string imgPath); void setTargetImagePath(string imgPath); Mat_<Vec3b> registration(int mergeMode); private: Mat getImgTransform(StarImagePart sourceImagePart, StarImagePart targetImagePart, Mat& OriImgHomo, bool& existHomo); }; <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.10 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /Applications/CLion.app/Contents/bin/cmake/bin/cmake # The command to remove a file. RM = /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration #============================================================================= # Targets provided globally by CMake. # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /Applications/CLion.app/Contents/bin/cmake/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." /Applications/CLion.app/Contents/bin/cmake/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/CMakeFiles /Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named ImageRegistration # Build rule for target. ImageRegistration: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 ImageRegistration .PHONY : ImageRegistration # fast build rule for target. ImageRegistration/fast: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/build .PHONY : ImageRegistration/fast StarImage.o: StarImage.cpp.o .PHONY : StarImage.o # target to build an object file StarImage.cpp.o: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImage.cpp.o .PHONY : StarImage.cpp.o StarImage.i: StarImage.cpp.i .PHONY : StarImage.i # target to preprocess a source file StarImage.cpp.i: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImage.cpp.i .PHONY : StarImage.cpp.i StarImage.s: StarImage.cpp.s .PHONY : StarImage.s # target to generate assembly for a file StarImage.cpp.s: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImage.cpp.s .PHONY : StarImage.cpp.s StarImagePart.o: StarImagePart.cpp.o .PHONY : StarImagePart.o # target to build an object file StarImagePart.cpp.o: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImagePart.cpp.o .PHONY : StarImagePart.cpp.o StarImagePart.i: StarImagePart.cpp.i .PHONY : StarImagePart.i # target to preprocess a source file StarImagePart.cpp.i: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImagePart.cpp.i .PHONY : StarImagePart.cpp.i StarImagePart.s: StarImagePart.cpp.s .PHONY : StarImagePart.s # target to generate assembly for a file StarImagePart.cpp.s: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImagePart.cpp.s .PHONY : StarImagePart.cpp.s StarImageRegistBuilder.o: StarImageRegistBuilder.cpp.o .PHONY : StarImageRegistBuilder.o # target to build an object file StarImageRegistBuilder.cpp.o: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImageRegistBuilder.cpp.o .PHONY : StarImageRegistBuilder.cpp.o StarImageRegistBuilder.i: StarImageRegistBuilder.cpp.i .PHONY : StarImageRegistBuilder.i # target to preprocess a source file StarImageRegistBuilder.cpp.i: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImageRegistBuilder.cpp.i .PHONY : StarImageRegistBuilder.cpp.i StarImageRegistBuilder.s: StarImageRegistBuilder.cpp.s .PHONY : StarImageRegistBuilder.s # target to generate assembly for a file StarImageRegistBuilder.cpp.s: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/StarImageRegistBuilder.cpp.s .PHONY : StarImageRegistBuilder.cpp.s Util.o: Util.cpp.o .PHONY : Util.o # target to build an object file Util.cpp.o: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/Util.cpp.o .PHONY : Util.cpp.o Util.i: Util.cpp.i .PHONY : Util.i # target to preprocess a source file Util.cpp.i: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/Util.cpp.i .PHONY : Util.cpp.i Util.s: Util.cpp.s .PHONY : Util.s # target to generate assembly for a file Util.cpp.s: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/Util.cpp.s .PHONY : Util.cpp.s main.o: main.cpp.o .PHONY : main.o # target to build an object file main.cpp.o: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/main.cpp.o .PHONY : main.cpp.o main.i: main.cpp.i .PHONY : main.i # target to preprocess a source file main.cpp.i: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/main.cpp.i .PHONY : main.cpp.i main.s: main.cpp.s .PHONY : main.s # target to generate assembly for a file main.cpp.s: $(MAKE) -f CMakeFiles/ImageRegistration.dir/build.make CMakeFiles/ImageRegistration.dir/main.cpp.s .PHONY : main.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... rebuild_cache" @echo "... edit_cache" @echo "... ImageRegistration" @echo "... StarImage.o" @echo "... StarImage.i" @echo "... StarImage.s" @echo "... StarImagePart.o" @echo "... StarImagePart.i" @echo "... StarImagePart.s" @echo "... StarImageRegistBuilder.o" @echo "... StarImageRegistBuilder.i" @echo "... StarImageRegistBuilder.s" @echo "... Util.o" @echo "... Util.i" @echo "... Util.s" @echo "... main.o" @echo "... main.i" @echo "... main.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>// // Created by 许舰 on 2018/3/11. // #include <sys/stat.h> #include "Util.h" Mat_<Vec3b> getTransformImgByHomo(Mat_<Vec3b>& queryImg, Mat homo) { //图像配准 Mat imageTransform; warpPerspective(queryImg, imageTransform, homo, Size(queryImg.cols, queryImg.rows)); return imageTransform; } /** * 按照 平均比例将图片叠加到一起 * @param sourceImages * @return */ Mat_<Vec3b> addMeanImgs(std::vector<Mat_<Vec3b>>& sourceImages) { Mat_<Vec3b> resImage; if (sourceImages.size() <= 0) { return resImage; } resImage = Mat(sourceImages[0].rows, sourceImages[0].cols, sourceImages[0].type()); for (int index = 0; index < sourceImages.size(); index ++) { resImage += (sourceImages[index] / sourceImages.size()); } return resImage; } Mat_<Vec3b> superimposedImg(vector<Mat_<Vec3b>>& images, Mat_<Vec3b>& trainImg) { int count = images.size(); Mat resImg; // 如果images没有图像,返回一个空的Mat if (count <= 0) { return resImg; } else if (count <= 1) { return images[0]; // 如果只有一幅图像,那么没有办法进行配准操作,直接返回唯一的一幅图像 } //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create( minHessian ); std::vector<KeyPoint> trainKeyPoints; detector->detect( trainImg, trainKeyPoints ); Ptr<SURF> extractor = SURF::create(); Mat trainDescriptors; extractor->compute(trainImg, trainKeyPoints, trainDescriptors); resImg = Mat::zeros(images[0].rows, images[0].cols, images[0].type()); for (int index = 1; index < count; index ++) { // 检测特征点以及特征点描述符 Mat_<Vec3b> queryImg = images[index]; std::vector<KeyPoint> queryKeyPoints; detector->detect( queryImg, queryKeyPoints ); Mat queryDescriptors; extractor->compute(queryImg, queryKeyPoints, queryDescriptors); // 生成匹配点信息 FlannBasedMatcher matcher; std::vector< vector<DMatch> > knnMatches; matcher.knnMatch(trainDescriptors, queryDescriptors, knnMatches, 2); // 筛选符合条件的特征点信息(最近邻次比率法) std::vector<DMatch> matches; vector<Point2f> queryMatchPoints, trainMatchPoints; // 用于存储已经匹配上的特征点对 for (int index = 0; index < knnMatches.size(); index ++) { DMatch firstMatch = knnMatches[index][0]; DMatch secondMatch = knnMatches[index][1]; if (firstMatch.distance < 0.75 * secondMatch.distance) { matches.push_back(firstMatch); trainMatchPoints.push_back(trainKeyPoints[firstMatch.queryIdx].pt); queryMatchPoints.push_back(queryKeyPoints[firstMatch.trainIdx].pt); } } // 计算映射关系 //获取图像1到图像2的投影映射矩阵 尺寸为3*3 Mat homo = findHomography(queryMatchPoints, trainMatchPoints, CV_RANSAC); //图像配准 Mat imageTransform; warpPerspective(queryImg, imageTransform, homo, Size(trainImg.cols, trainImg.rows)); resImg += (imageTransform / count); } return resImg; } Mat_<Vec3b> superimposedImg(Mat_<Vec3b>& queryImg, Mat_<Vec3b>& trainImg) { //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create(minHessian); std::vector<KeyPoint> trainKeyPoints; detector->detect(trainImg, trainKeyPoints); Ptr<SURF> extractor = SURF::create(); Mat trainDescriptors; extractor->compute(trainImg, trainKeyPoints, trainDescriptors); // 检测特征点以及特征点描述符 std::vector<KeyPoint> queryKeyPoints; detector->detect(queryImg, queryKeyPoints); Mat queryDescriptors; extractor->compute(queryImg, queryKeyPoints, queryDescriptors); // 生成匹配点信息 FlannBasedMatcher matcher; std::vector<vector<DMatch> > knnMatches; matcher.knnMatch(trainDescriptors, queryDescriptors, knnMatches, 2); // 筛选符合条件的特征点信息(最近邻次比率法) std::vector<DMatch> matches; vector<Point2f> queryMatchPoints, trainMatchPoints; // 用于存储已经匹配上的特征点对 for (int index = 0; index < knnMatches.size(); index++) { DMatch firstMatch = knnMatches[index][0]; DMatch secondMatch = knnMatches[index][1]; if (firstMatch.distance < 0.75 * secondMatch.distance) { matches.push_back(firstMatch); trainMatchPoints.push_back(trainKeyPoints[firstMatch.queryIdx].pt); queryMatchPoints.push_back(queryKeyPoints[firstMatch.trainIdx].pt); } } // 计算映射关系 //获取图像1到图像2的投影映射矩阵 尺寸为3*3 Mat homo = findHomography(queryMatchPoints, trainMatchPoints, CV_RANSAC); //图像配准 Mat imageTransform; warpPerspective(queryImg, imageTransform, homo, Size(trainImg.cols, trainImg.rows)); return imageTransform; } int getFiles(string path, vector<string>& files) { unsigned char isFile =0x8; DIR* p_dir; const char* str = path.c_str(); p_dir = opendir(str); if (p_dir == NULL) { cout << "can't open " + path << endl; return -1; } struct dirent* p_dirent; while (p_dirent = readdir(p_dir)) { if (p_dirent->d_type == isFile) { // 该file是文件信息 string tmpFileName = p_dirent->d_name; if (tmpFileName =="." || tmpFileName == "..") { continue; } else { // 获取文件状态信息 struct stat buf; int result; result = stat(tmpFileName.c_str(), &buf); if (result == 0) { cout << "文件状态信息出错, " + tmpFileName << endl; return -1; } else { cout << tmpFileName << endl; cout << buf.st_ctimespec.tv_sec << endl; cout << buf.st_mtimespec.tv_sec << endl; } files.push_back(path + "/" + tmpFileName); } } } closedir(p_dir); sort(files.begin(), files.end()); return (int)files.size(); } <file_sep>#include <iostream> #include <opencv/cv.hpp> #include "opencv2/xfeatures2d.hpp" #include "StarImageRegistBuilder.h" #include "Util.h" using namespace cv; using namespace cv::xfeatures2d; using namespace std; //bool compare(Vec3b a, Vec3b b); Mat process(std::vector<Mat_<Vec3b>> sourceImages, Mat_<Vec3b> targetImage) { Mat groundMaskImgMat = imread("/Users/xujian/Desktop/JPEG_20180618_074240_C++.jpg", IMREAD_UNCHANGED); Mat skyMaskMat = ~groundMaskImgMat; imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0101.jpg", skyMaskMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0102.jpg", groundMaskImgMat); // 目标矩阵的操作 Mat_<Vec3b> skyImgMat; targetImage.copyTo(skyImgMat, skyMaskMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0103.jpg", skyImgMat); Mat_<Vec3b> groundImgMat; targetImage.copyTo(groundImgMat, groundMaskImgMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0104.jpg", groundImgMat); // 源矩阵的操作 std::vector<Mat_<Vec3b>> skyImgs; for (int i = 0; i < sourceImages.size(); i ++) { Mat mat = sourceImages[i]; Mat skyPartMat; mat.copyTo(skyPartMat, skyMaskMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0105.jpg", skyPartMat); skyImgs.push_back(skyPartMat); } std::vector<Mat_<Vec3b>> groundImgs; for (int i = 0; i < sourceImages.size(); i ++) { Mat mat = sourceImages[i]; Mat groundPartMat; mat.copyTo(groundPartMat, groundMaskImgMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0106.jpg", groundPartMat); groundImgs.push_back(groundPartMat); } int rowParts = 5; int columnParts = 5; StarImageRegistBuilder starImageRegistBuilder = StarImageRegistBuilder(skyImgMat, skyImgs, skyMaskMat, rowParts, columnParts); Mat_<Vec3b> resultImage = starImageRegistBuilder.registration(StarImageRegistBuilder::MERGE_MODE_MEAN); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0107.jpg", resultImage); Mat skyRes; resultImage.copyTo(skyRes, skyMaskMat); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0108.jpg", skyRes); Mat groundRes; groundImgs.push_back(groundImgMat); addMeanImgs(groundImgs).copyTo(groundRes, groundMaskImgMat); // addWeighted(groundImgMat, 0.5, groundImgs[0], 0.5, 0, groundRes); Mat finalRes = skyRes | groundRes; // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image-" + std::to_string(index) + ".jpg", finalRes); return finalRes; } /** @function main */ int main(int argc, char** argv) { vector<string> files; string folder = "/Users/xujian/Downloads/11"; getFiles(folder, files); if (files.size() <= 0) { return -1; } int targetIndex = (int)(files.size() / 2); string targetImgPath = files[files.size() / 2]; Mat_<Vec3b> targetImage = imread(targetImgPath, IMREAD_UNCHANGED); // 多张整合成一张照片的逻辑 std::vector<Mat_<Vec3b>> sourceImages; for (int i = 0 ; i < files.size(); i ++) { if (i == targetIndex) { continue; } if (i != 3) { continue; } cout << files[i] << endl; sourceImages.push_back(imread(files[i], IMREAD_UNCHANGED)); } Mat tmpResult = process(sourceImages, targetImage); // 以后的逻辑中, sourceImages不是vector,而变成了一个string的图片路径 imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image.jpg", tmpResult); // // 11 张结果照片的逻辑 // for (int index = 0; index < targetIndex; index ++) { // string sourceImgPath = files[index]; // std::vector<Mat_<Vec3b>> sourceImages; // sourceImages.push_back(imread(sourceImgPath, IMREAD_UNCHANGED)); // // for (int j = index + 1; j < targetIndex; j ++) { // Mat_<Vec3b> tmpResult = imread(files[j], IMREAD_UNCHANGED); // sourceImages[0] = process(sourceImages, tmpResult); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/test/"+ std::to_string(j)+".jpg", sourceImages[0]); // } // // Mat tmpResult = process(sourceImages, targetImage); // 以后的逻辑中, sourceImages不是vector,而变成了一个string的图片路径 // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image-" + std::to_string(index) + ".jpg", tmpResult); // } // // for (int index = (int)files.size() - 1; index > targetIndex; index --) { // string sourceImgPath = files[index]; // std::vector<Mat_<Vec3b>> sourceImages; // sourceImages.push_back(imread(sourceImgPath, IMREAD_UNCHANGED)); // // for (int j = index; j < targetIndex; j ++) { // Mat_<Vec3b> tmpResult = imread(files[j], IMREAD_UNCHANGED); // sourceImages[0] = process(sourceImages, tmpResult); // } // // Mat tmpResult = process(sourceImages, targetImage); // 以后的逻辑中, sourceImages不是vector,而变成了一个string的图片路径 // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image-" + std::to_string(index) + ".jpg", tmpResult); // } } ///** @function main */ //int main( int argc, char** argv ) //{ // // vector<string> files; // string folder = "/Users/xujian/Downloads/11"; // getFiles(folder, files); // //// string sourceImgPath1 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/b1-1Y8A4155.jpg"; // string targetImgPath = "/Users/xujian/Downloads/1Y1.JPG"; // string sourceImgPath2 = "/Users/xujian/Downloads/1Y6.JPG"; // // Mat_<Vec3b> targetImage = imread(targetImgPath, IMREAD_UNCHANGED); // std::vector<Mat_<Vec3b>> sourceImages; //// sourceImages.push_back(imread(sourceImgPath1, IMREAD_UNCHANGED)); // sourceImages.push_back(imread(sourceImgPath2, IMREAD_UNCHANGED)); // // Mat groundMaskImgMat = imread("/Users/xujian/Desktop/JPEG_20180618_074240_C++.jpg", IMREAD_UNCHANGED); //// Mat groundMaskImgMat ; //// groundMaskImgMat.create(groundMaskImgMat_.size(), CV_8UC1); //// groundMaskImgMat = groundMaskImgMat_ & 1; // Mat skyMaskMat = ~groundMaskImgMat; // // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0101.jpg", skyMaskMat); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0102.jpg", groundMaskImgMat); // // // 目标矩阵的操作 // Mat_<Vec3b> skyImgMat; // targetImage.copyTo(skyImgMat, skyMaskMat); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0103.jpg", skyImgMat); // // Mat_<Vec3b> groundImgMat; // targetImage.copyTo(groundImgMat, groundMaskImgMat); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0104.jpg", groundImgMat); // // // 源矩阵的操作 // std::vector<Mat_<Vec3b>> skyImgs; // for (int i = 0; i < sourceImages.size(); i ++) { // Mat mat = sourceImages[i]; // Mat skyPartMat; // mat.copyTo(skyPartMat, skyMaskMat); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0105.jpg", skyPartMat); // skyImgs.push_back(skyPartMat); // } // // std::vector<Mat_<Vec3b>> groundImgs; // for (int i = 0; i < sourceImages.size(); i ++) { // Mat mat = sourceImages[i]; // Mat groundPartMat; // mat.copyTo(groundPartMat, groundMaskImgMat); // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0106.jpg", groundPartMat); // groundImgs.push_back(groundPartMat); // } // // int rowParts = 5; // int columnParts = 5; // // StarImageRegistBuilder starImageRegistBuilder = StarImageRegistBuilder(skyImgMat, skyImgs, skyMaskMat, rowParts, columnParts); // Mat_<Vec3b> resultImage = starImageRegistBuilder.registration(StarImageRegistBuilder::MERGE_MODE_MEAN); // // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0107.jpg", resultImage); // // Mat skyRes; // resultImage.copyTo(skyRes, skyMaskMat); // // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0108.jpg", skyRes); // // Mat groundRes; // addWeighted(groundImgMat, 0.5, groundImgs[0], 0.5, 0, groundRes); //// Mat groundRes_ = superimposedImg(groundImgs, groundImgMat); //// Mat groundRes; //// groundRes_.copyTo(groundRes, groundMaskImgMat); // // Mat finalRes = skyRes | groundRes; // // imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image.jpg", finalRes); // //} //bool compare(Vec3b a, Vec3b b) { // for (int i = 0; i < 3; i++) { // // cout << "a" << std::to_string(i) << std::to_string(a[i]) << "\t" << "b" << std::to_string(i) << std::to_string(b[i]) << endl; // // if (a[i] != b[i]) { // return false; // } // } // return true; //} /** string sourceImgPath = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/a1-1Y8A0106.jpg"; string targetImgPath = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/a2-1Y8A0108.jpg"; Mat_<Vec3b> img_1 = imread( sourceImgPath, IMREAD_UNCHANGED ); Mat_<Vec3b> img_2 = imread( targetImgPath, IMREAD_UNCHANGED ); int type = img_1.type(); if( !img_1.data || !img_2.data ) { std::cout<< " --(!) Error reading images " << std::endl; return -1; } //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create( minHessian ); std::vector<KeyPoint> keypoints_1, keypoints_2; Mat img_1 = skyImgMat; Mat img_2 = skyImgs[0]; detector->detect( img_1, keypoints_1 ); detector->detect( img_2, keypoints_2 ); // SurfDescriptorExtractor extractor; Ptr<SURF> extractor = SURF::create(); Mat descriptors_1, descriptors_2; extractor->compute(img_1, keypoints_1, descriptors_1); extractor->compute(img_2, keypoints_2, descriptors_2); //-- Step 2: Matching descriptor vectors using FLANN matcher FlannBasedMatcher matcher; std::vector< vector<DMatch> > knnMatches; matcher.knnMatch(descriptors_1, descriptors_2, knnMatches, 2); std::vector<DMatch> matches_; for (int index = 0; index < knnMatches.size(); index ++) { DMatch firstMatch = knnMatches[index][0]; DMatch secondMatch = knnMatches[index][1]; if (firstMatch.distance < 0.75 * secondMatch.distance) { matches_.push_back(firstMatch); } } sort(matches_.begin(), matches_.end()); std::vector<DMatch> matches; vector<Point2f> imagePoints1, imagePoints2; for (int index = 0; index < matches_.size(); index ++) { cout << matches_[index].distance << "\n"; int y1 = keypoints_1[matches_[index].queryIdx].pt.y + 288; int y2 = keypoints_2[matches_[index].trainIdx].pt.y + 288; int x1 = keypoints_1[matches_[index].queryIdx].pt.x; int x2 = keypoints_2[matches_[index].trainIdx].pt.x; if (y2 > skyImgMat.rows || y1 > skyImgMat.rows) { continue; } if (skyMaskMat.at<uchar>(y2, x2) == 0 || skyMaskMat.at<uchar>(y1, x1) == 0) { continue; } matches.push_back(matches_[index]); imagePoints1.push_back(keypoints_1[matches_[index].queryIdx].pt); imagePoints2.push_back(keypoints_2[matches_[index].trainIdx].pt); } Mat img_matches; drawMatches( img_1, keypoints_1, img_2, keypoints_2, matches, img_matches ); string matchPath = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/0101test.jpg"; imwrite(matchPath, img_matches); //获取图像1到图像2的投影映射矩阵 尺寸为3*3 Mat homo=findHomography(imagePoints1,imagePoints2,CV_RANSAC); ////也可以使用getPerspectiveTransform方法获得透视变换矩阵,不过要求只能有4个点,效果稍差 //Mat homo=getPerspectiveTransform(imagePoints1,imagePoints2); cout<<"变换矩阵为:\n"<<homo<<endl<<endl; //输出映射矩阵 //图像配准 Mat imageTransform1,imageTransform2; warpPerspective(img_1,imageTransform1,homo,Size(img_2.cols,img_2.rows)); imshow("经过透视矩阵变换后",imageTransform1); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image-transform.jpg", imageTransform1); Mat imageResult; addWeighted(imageTransform1, 0.5, img_2, 0.5, 0, imageResult); imwrite("/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/result-image.jpg", imageResult); waitKey(0); return 0; * */<file_sep>// // Created by 许舰 on 2018/1/11. // #include "StarImageRegistBuilder.h" #include "Util.h" /** * * @param targetImage: train image * @param sourceImages: query image * @param rowParts * @param columnParts */ StarImageRegistBuilder::StarImageRegistBuilder(Mat_<Vec3b>& targetImage, std::vector<Mat_<Vec3b>>& sourceImages, Mat& skyMaskMat, int rowParts, int columnParts) { this->rowParts = rowParts; this->columnParts = columnParts; this->imageCount = (int)sourceImages.size() + 1; this->skyMaskMat = skyMaskMat; this->skyBoundaryRange = (int)(skyMaskMat.rows * 0.005); this->targetImage = targetImage; this->sourceImages = sourceImages; // 开始对每一张图片进行分块操作 for (int index = 0; index < sourceImages.size(); index ++) { StarImage starImage = StarImage(sourceImages[index], this->rowParts, this->columnParts); this->sourceStarImages.push_back(starImage); } this->targetStarImage = StarImage(targetImage, this->rowParts, this->columnParts); } /** * * @param imgPath */ void StarImageRegistBuilder::addSourceImagePath(string imgPath) { /** * 必须首先调用 addTargetImagePath。 * 如果图片大小和targetImage不相同,那么不能加入图片 */ Mat image = imread(imgPath, IMREAD_UNCHANGED); if (image.rows != targetStarImage.getImage().rows || image.cols != targetStarImage.getImage().cols) { return; } this->sourceStarImages.push_back(StarImage(image, this->rowParts, this->columnParts)); } /** * * @param imgPath */ void StarImageRegistBuilder::setTargetImagePath(string imgPath) { this->targetStarImage = StarImage(imread(imgPath, IMREAD_UNCHANGED), this->rowParts, this->columnParts); } /** * * @return */ Mat_<Vec3b> StarImageRegistBuilder::registration(int mergeMode) { // 最终配准的图像信息 StarImage resultStarImage = StarImage(Mat(this->targetStarImage.getImage().rows, this->targetStarImage.getImage().cols, this->targetStarImage.getImage().type(), cv::Scalar(0, 0, 0)), this->rowParts, this->columnParts, true); // true 表示 clone,深拷贝,不然会出现图片重叠的现象 // 开始对图像的每一个部分进行对齐操作,分别与targetStarImage 做对比 for (int index = 0; index < this->sourceStarImages.size(); index ++) { StarImage tmpStarImage = this->sourceStarImages[index]; // 直接赋值,不是指针操作, // 对于每一小块图像都做配准操作 for (int rPartIndex = 0; rPartIndex < this->rowParts; rPartIndex ++) { for (int cPartIndex = 0; cPartIndex < this->columnParts; cPartIndex ++) { // Mat_<Vec3b> sourceImg = resultStarImage.getImage(); // string sfile1 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/sourceImg/" + std::to_string(index) + "_" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; // imwrite(sfile1, sourceImg); Mat homo; bool existHomo = false; // cout << "registration: " << std::to_string(rPartIndex) + " " + std::to_string(cPartIndex) << endl; Mat tmpRegistMat = this->getImgTransform(tmpStarImage.getStarImagePart(rPartIndex, cPartIndex), this->targetStarImage.getStarImagePart(rPartIndex, cPartIndex), homo, existHomo); // this->targetStarImage.getStarImagePart(rPartIndex, cPartIndex), homo, existHomo); // this->sourceStarImages[index].setStarImagePart(rPartIndex, cPartIndex, tmpRegistMat); Mat_<Vec3b>& queryImgTransform = this->sourceImages[index]; if (existHomo) { queryImgTransform = getTransformImgByHomo(queryImgTransform, homo); } else { queryImgTransform = this->targetImage; } string sfile = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/queryImgTransform/" + std::to_string(index) + "_" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(sfile, queryImgTransform); // Mat_<Vec3b> sourceImg = this->sourceStarImages[index].getStarImagePart(rPartIndex, cPartIndex).getImage(); // Mat_<Vec3b> sourceImg = resultStarImage.getStarImagePart(rPartIndex, cPartIndex).getImage(); string sfile1 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/sourceImg/" + std::to_string(index) + "_" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(sfile1, tmpRegistMat); resultStarImage.getStarImagePart(rPartIndex, cPartIndex).addImagePixelValue(tmpRegistMat, queryImgTransform, this->skyMaskMat, this->imageCount); Mat_<Vec3b> sourceImg1 = resultStarImage.getStarImagePart(rPartIndex, cPartIndex).getImage(); string sfile2 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/addImagePixelValue/" + std::to_string(index) + "_" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(sfile2, sourceImg1); } } } // 对于配准图像和待配准图像做平均值操作(先买上目标图像的那一部分,这一段代码不能放在source整合的前面,不然图片会出现缝隙,原因待查) for (int rPartIndex = 0; rPartIndex < this->rowParts; rPartIndex ++) { for (int cPartIndex = 0; cPartIndex < this->columnParts; cPartIndex++) { Mat_<Vec3b> targetImg = this->targetStarImage.getStarImagePart(rPartIndex, cPartIndex).getImage(); resultStarImage.getStarImagePart(rPartIndex, cPartIndex).addImagePixelValue(targetImg, this->targetImage, this->skyMaskMat, this->imageCount); } } // 对配准好的图像进行整合 return resultStarImage.mergeStarImageParts(); } /** * * @param sourceImagePart * @param targetImagePart * @return */ Mat StarImageRegistBuilder::getImgTransform(StarImagePart sourceImagePart, StarImagePart targetImagePart, Mat& oriImgHomo, bool& existHomo) { Mat sourceImg = sourceImagePart.getImage(); // query image Mat targetImg = targetImagePart.getImage(); // train image // 取出当前mask起始点的位置 int rMaskIndex = sourceImagePart.getRowPartIndex() * sourceImg.rows; int cMaskIndex = sourceImagePart.getColumnPartIndex() * sourceImg.cols; // if( !sourceImg.data || !targetImg.data ) // { std::cout<< " --(!) Error loading images " << std::endl; return NULL; } //-- Step 1: Detect the keypoints using SURF Detector, compute the descriptors int minHessian = 400; Ptr<SURF> detector = SURF::create( minHessian ); std::vector<KeyPoint> keypoints_1, keypoints_2; detector->detect( sourceImg, keypoints_1 ); detector->detect( targetImg, keypoints_2 ); // SurfDescriptorExtractor extractor; Ptr<SURF> extractor = SURF::create(); Mat descriptors_1, descriptors_2; extractor->compute(sourceImg, keypoints_1, descriptors_1); extractor->compute(targetImg, keypoints_2, descriptors_2); //-- Step 2: Matching descriptor vectors using FLANN matcher FlannBasedMatcher matcher; std::vector< vector<DMatch> > knnMatches; try { /** * 经过调试,发现照片有些部分是全暗的,根本无法找到特征点,这个时候 FlannBasedMatcher 会报 * opencv knnMatch error: (-210) type=0 */ matcher.knnMatch(descriptors_1, descriptors_2, knnMatches, 2); } catch (cv::Exception) { return sourceImg; // 直接采集source img的信息。 } // 1. 最近邻次比律法,取出错误匹配点 std::vector<DMatch> tempMatches; // 符合条件的匹配对 for (int index = 0; index < knnMatches.size(); index ++) { DMatch firstMatch = knnMatches[index][0]; DMatch secondMatch = knnMatches[index][1]; if (firstMatch.distance < 0.9 * secondMatch.distance) { tempMatches.push_back(firstMatch); } } // 2. 对应 query image中的多个特征点对应 target image中的同一个特征点的情况(导致计算出的映射关系不佳),只取最小的匹配 vector<Point2f> imagePoints1, imagePoints2; std::map<int, DMatch> matchRepeatRecords; for (int index = 0; index < tempMatches.size(); index ++) { cout << tempMatches[index].distance << "\n"; // int queryIdx = matches[index].queryIdx; int trainIdx = tempMatches[index].trainIdx; // 记录标准图像中的每个点被配准了多少次,如果被配准多次,那么说明这个特征点匹配不合格 if (matchRepeatRecords.count(trainIdx) <= 0) { matchRepeatRecords[trainIdx] = tempMatches[index]; } else { // 多个query image的特征点对应 target image的特征点时,只取距离最小的一个匹配(这个算是双向匹配的改进) if (matchRepeatRecords[trainIdx].distance > tempMatches[index].distance) { matchRepeatRecords[trainIdx] = tempMatches[index]; } } } // 3. 计算匹配特征点对的标准差信息(标准差衡量标准之间只有相互的,那么要将标准差,以及match等一切中间过程存储起来,之后再进行配准,太耗内存) std::map<int, DMatch>::iterator iter; // std::vector<double> matchDist; // double matchDistCount = 0.0; // dist数组个数 // double matchDistSum = 0.0; // dist数组总和 // double matchDistMean = 0.0; // dist数组平均值 // for (iter = matchRepeatRecords.begin(); iter != matchRepeatRecords.end(); iter ++) { // matchDistSum += iter->second.distance; // matchDistCount += 1; // } // matchDistMean = matchDistSum / matchDistCount; // double matchDistAccum = 0.0; // for (iter = matchRepeatRecords.begin(); iter != matchRepeatRecords.end(); iter ++) { // double distance = iter->second.distance; // matchDistAccum += (distance - matchDistMean) * (distance - matchDistMean); // } // double matchDistStdev = sqrt(matchDistAccum / (matchDistCount - 1)); // 3.1 获取准确的最大最小值 double maxMatchDist = 0; double minMatchDist = 100; for (iter = matchRepeatRecords.begin(); iter != matchRepeatRecords.end(); iter ++) { if (iter->second.distance < minMatchDist) { minMatchDist = iter->second.distance; } if (iter->second.distance > maxMatchDist) { maxMatchDist = iter->second.distance; } } // 4. 根据特征点匹配对,分离出两幅图像中已经被匹配的特征点 std::vector<DMatch> matches; double matchThreshold = minMatchDist + (maxMatchDist - minMatchDist) * 0.1; // 阈值越大,留下的特征点越多(这个阈值是一个做文章的地方) double slopeThreshold = 0.3; for (iter = matchRepeatRecords.begin(); iter != matchRepeatRecords.end(); iter ++) { DMatch match = iter->second; int queryIdx = match.queryIdx; int trainIdx = match.trainIdx; // 将检测出的靠近边缘的特征点去除 int qy = (int)(keypoints_1[queryIdx].pt.y + this->skyBoundaryRange + rMaskIndex), ty = (int)(keypoints_2[trainIdx].pt.y + this->skyBoundaryRange + rMaskIndex); int qx = (int)(keypoints_1[queryIdx].pt.x + cMaskIndex), tx = (int)(keypoints_2[trainIdx].pt.x + cMaskIndex); if (qy >= this->skyMaskMat.rows || ty >= this->skyMaskMat.rows) { continue; // Mat.at(行数, 列数) } else if ( this->skyMaskMat.at<uchar>(qy, qx) == 0 || this->skyMaskMat.at<uchar>(ty, tx) == 0 ) { continue; } // 5. 设置 匹配点之间的 distance 阈值来选出 质量好的特征点(方差策略的替代方案) // 6. 计算两个匹配点之间的斜率 double slope = abs( (keypoints_1[queryIdx].pt.y - keypoints_2[trainIdx].pt.y) * 1.0 / (keypoints_1[queryIdx].pt.x - (keypoints_2[trainIdx].pt.x + targetImg.cols) ) ); // && iter->second.distance < matchThreshold if ( slope < slopeThreshold && iter->second.distance < matchThreshold) { matches.push_back(iter->second); imagePoints1.push_back(keypoints_1[queryIdx].pt); imagePoints2.push_back(keypoints_2[trainIdx].pt); } } // 测试代码: Mat img_matches; drawMatches( sourceImg, keypoints_1, targetImg, keypoints_2, matches, img_matches ); int rPartIndex = sourceImagePart.getRowPartIndex(); int cPartIndex = sourceImagePart.getColumnPartIndex(); string sfile1 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/01/" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; string sfile2 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/02/" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(sfile1, sourceImg); imwrite(sfile2, targetImg); string matchPath = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/match/" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(matchPath, img_matches); int IMG_MATCH_POINT_THRESHOLD = 10; // 这里是个做文章的地方 // 对应图片部分中没有特征点的情况(导致计算出的映射关系不佳,至少要4对匹配点才能计算出匹配关系) if (imagePoints1.size() >= IMG_MATCH_POINT_THRESHOLD && imagePoints2.size() < IMG_MATCH_POINT_THRESHOLD) { // 没有特征点信息,那么说明这个区域是没有特征的,所以返回 查询图片部分,作为内容填充 return sourceImg; } else if (imagePoints1.size() < IMG_MATCH_POINT_THRESHOLD && imagePoints2.size() >= IMG_MATCH_POINT_THRESHOLD) { return targetImg; } else if (imagePoints1.size() < IMG_MATCH_POINT_THRESHOLD && imagePoints2.size() < IMG_MATCH_POINT_THRESHOLD) { return targetImg; // 特征点都不足时,以targetImage为基础进行的配准 } // 获取图像1到图像2的投影映射矩阵 尺寸为3*3 Mat homo = findHomography(imagePoints1, imagePoints2, CV_RANSAC); // 也可以使用getPerspectiveTransform方法获得透视变换矩阵,不过要求只能有4个点,效果稍差 // Mat homo = getPerspectiveTransform(imagePoints1,imagePoints2); cout<< "变换矩阵为:\n" << homo << endl << endl; //输出映射矩阵 /** * 这里如果有一副图片中的特征点过少,导致查询图片部分 中的多个特征点直接 和 目标图片部分 中的同一个特征点相匹配, * 那么会导致算不出变换矩阵,变换矩阵为 [] 。导致错误。 */ if (homo.rows < 3 || homo.cols < 3) { existHomo = false; if (imagePoints1.size() > imagePoints2.size()) { return sourceImg; // 因为是星空图片,移动不会很大,在目标图片部分的特征点几乎没有的情况下,那么直接返回待配准图像进行填充细节。 } else { return targetImg; } } oriImgHomo = homo; existHomo = true; //图像配准 Mat sourceImgTransform; warpPerspective(sourceImg, sourceImgTransform ,homo , Size(targetImg.cols, targetImg.rows)); string sfile3 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/translatre/" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; imwrite(sfile3, sourceImgTransform); // Mat testMask = ~ sourceImgTransform; // Mat boundary; // sourceImg.copyTo(boundary, testMask); // string sfile4 = "/Users/xujian/Workspace/AndroidStudy/CPlusPlus/ImageRegistration/img/boundary/" + std::to_string(rPartIndex) + "_" + std::to_string(cPartIndex) + ".jpg"; // imwrite(sfile4, boundary); return sourceImgTransform; }
21ac40688b698a01c2c31b66d5ad34cb5ab7a94c
[ "Makefile", "CMake", "C++" ]
6
CMake
XuJian1252878/PhotorImg
d481aac0b6d3789804d29fba96e71bbdd9389162
db98412db7b1f695cf7983bf3804068e35ef321d
refs/heads/master
<file_sep>#include<iostream> using namespace std; bool res7(int n) { //cout<<n<<endl; if(n%7==0) return true; if(n%10 == 7 || n/10 ==7) return true; if((n/10)%10 ==7 || n/100==7)return true; else return false; } int main() { // cout<<"input:"<<endl; int n; cin>>n; int a[4]={0}; // cout<<"print a "<<a[0]<<endl; int num=0,i=1; // cout<<n<<endl; while(n--) { if(res7(i)){ i++; a[num]++; num++; num=num%4; n++; } else { i++; num++; num=num%4; } } cout<<a[0]<<endl; cout<<a[1]<<endl; cout<<a[2]<<endl; cout<<a[3]<<endl; return 0; }<file_sep>#include<bits/stdc++.h> using namespace std; bool judge(string str) { queue<int> q; stack<int> s; for(int i=0;i<str.size();i++) { if(str[i]>='0'&& str[i]<='9') q.push(str[i]-'0'); if(str[i]=='+')q.push(-1); if(str[i]=='-')q.push(-2); if(str[i]=='x')q.push(-3); if(str[i]=='/')q.push(-4); cout<<q.back()<<"\t"; } cout<<" :q"<<endl; int temp; while(!q.empty()) { if(q.front()==-3) { q.pop(); temp=s.top()*q.front(); s.pop(); s.push(temp); cout<<q.front()<<'\t'<<"temp: "<<temp<<endl; q.pop(); } else if(q.front()==-4) { q.pop(); temp=s.top()/q.front(); s.pop(); s.push(temp); cout<<q.front()<<'\t'<<"temp: "<<temp<<endl;; q.pop(); } //if((q.front()>='0'&& q.front()<='9')||q.front()=='+'-'0' || q.front()=='-'-'0') else { s.push(q.front()); q.pop(); } //q.pop(); } stack<int> ss; //s.pop(); cout<<"s.size: "<<s.size()<<endl; while(!s.empty()) { ss.push(s.top());cout<<s.top()<<" "; s.pop(); } cout<<"size: "<<ss.size()<<endl; int sum=ss.top(); ss.pop(); while(!ss.empty()) { if(ss.top()==-1) { ss.pop(); sum =sum+ ss.top(); ss.pop(); } else if(ss.top()==-2) { ss.pop(); sum=sum-ss.top(); ss.pop(); } else { sum=ss.top(); ss.pop(); } cout<<ss.size()<<" :"<<sum<<endl; } if (sum==24)return true; else return false; } int main() { string str; int n; cin >>n; for(int i=0;i<n;i++) { cin>>str; if(judge(str))cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }<file_sep># ccf-code [算法思维系列 ebook](https://labuladong.github.io/ebook) [labuladong的算法小抄](https://labuladong.gitbook.io/algo/) some studying codes to solve ccf problems using CC first and a test for git version control version 2 ![laptop](assets/laptop.png) ## Test code #include <iostream> using namespace std; int main() { cout<<"hello world"<<endl; return 0; } - test - test1 - test2 ```mermaid graph TD A-->B A-->C B-->D C-->D ``` ```flow st=>start: 开始 op=>operation: My operation cond=>condition: Yes or No? e=>end: 结束 st->op->cond cond(yes)->e cond(no)->op ``` <file_sep>#include <iostream> #include <cmath> using namespace std; int camp(int a, int b) { if (a > b) return 1; if (a < b) return -1; else return 0; } string changeC2N(string str) { int i = 0; string s; while (str[i]) { switch (str[i]) { case 'A': s = s + '1'; break; case 'T': s = s + '2'; break; case 'G': s = s + '3'; break; case 'C': s = s + '4'; break; default: break; } i++; } return s; } int **change2M(string str) { int i, j, n = str.length(); int **arr = new int *[n]; for (i = 0; i < n; i++) { arr[i] = new int[n]; for (j = 0; j < n; j++) { // cout << a[i] << a[j] << " : "; cout << camp(str[i], str[j]) << " "; arr[i][j] = camp(str[i], str[j]); } cout << endl; } return arr; } double dSL(int **a, int **b, int m, int n) { double res; int sum = 0; if (m == n) { cout << "if two string length is equal,this is the end" << endl; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { sum += pow(abs(a[i][j] - b[i][j]), 2); } res = sqrt(sum) / (2 * n * (n - 1)); } else { } return res; } int main() { int n, i, j; string str1, str2; cout << "print str1:"; cin >> str1; // str1 = "GCTA"; // str2 = "ATGC"; cout << "print str2:"; cin >> str2; // cout << str1 << "\t" << changeC2N(str1) << "\t" << str1.length() << endl; cout << "A 矩阵结果" << endl; int **a = change2M(changeC2N(str1)); cout << "B 矩阵结果" << endl; int **b = change2M(changeC2N(str2)); // cout << a[2][3] + a[1][3] << endl; // cout << abs(-90) << endl; cout << dSL(a, b, str1.length(), str2.length()) << endl; return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; bool judge(string str) { bool res=false; queue<int>num; queue<char>op; for(int i=0;i<7;i++) { if(str[i]>='0' && str[i]<='9') { num.push(str[i]-'0'); } else if(str[i]=='x') { num.push(num.back()*(str[++i]-'0')); } else if(str[i]=='/') { num.push(num.back()/(str[++i]-'0')); } else { op.push(str[i]); } } int sum=num.front(); num.pop(); while(!op.empty()) { if(op.front()=='+') { sum=sum+num.front(); num.pop(); op.pop(); } else if(op.front()=='-') { sum=sum-num.front(); num.pop(); op.pop(); } } if (sum==24)res=true; return res; } int main() { string str; int n; cin>>n; for(int i=0;i<n;i++) { cin>>str; if(judge(str))cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; int f(int n, int m) { if (n == 1) return n; else { return (f(n - 1, m) + m - 1) % n + 1; } } int main() { int n, k; cin >> n >> k; cout << f(n, k) << endl; int a[5] = {1, 2, 3, 3, 1}; int temp = a[0]; for (int i = 1; i < 5; i++) temp = temp ^ a[i]; cout << temp << "\n"; return 0; }
0bd8f018b10d40bb7cee36f03a20ba89ef82629c
[ "Markdown", "C++" ]
6
C++
SiYuenYip/ccf-code
2e405735d7d5fdf8d4c153157e7eb93c8992fe4a
e81e28bbf1511972d6f2bfcfd951c98186358eb2
refs/heads/master
<file_sep>/** * Created by Dell on 9/18/17. */ var app = angular.module('myApp', ["ngRoute"]); app.config(function($routeProvider) { $routeProvider .when("/emp", { templateUrl : "employee.html" }) .when("/add", { templateUrl : "signup.html", controller : "addCtrl" }) /*.when("/edit", { templateUrl : "edit.html", controller : "editCtrl" })*/ .when("/login", { templateUrl : "login.html", controller : "loginCtrl" }); }); app.service("dataService",function ($http) { this.myFun = function() { return $http.get("MOCK_DATA.JSON"); }; this.temp = null; this.object = {}; }); app.controller("empCtrl", function ($scope,dataService,$location) { dataService.myFun().then(function (response) { $scope.myData = response.data.myData; dataService.object = $scope.myData; }); $scope.removeInput = function (index) { dataService.object.splice(index, 1); }; $scope.add = function () { $location.path('/add'); dataService.temp = null; }; $scope.editInput = function (index) { dataService.temp = index; $location.path('/add'); }; }); app.controller("addCtrl", function ($scope,$location,dataService) { $scope.msg = "Welcome"; $scope.user={}; /*$scope.user={};*/ $scope.user = dataService.object[dataService.temp]; if (!dataService.temp) { $scope.addInput = function() { $location.path('/emp'); dataService.object.push($scope.user); $scope.user = ""; } } else { $scope.addInput = function () { dataService.object[dataService.temp] = $scope.user; $location.path("/emp"); } } /*$scope.addInput = function() { $scope.myData.push( { 'id' : $scope.empid , 'gender' : $scope.gen, 'name' : $scope.nam, 'email' : $scope.eml, 'city' : $scope.ct }); $scope.empid =""; $scope.gen = ""; $scope.nam = ""; $scope.eml = ""; $scope.ct = ""; };*/ }); /*app.controller("editCtrl", function ($scope,$location,dataService) { $scope.msg = "Update Details"; $scope.user = dataService.object[dataService.temp]; $scope.updateInput = function () { dataService.object[dataService.temp] = $scope.user; $location.path("/emp"); }; });*/ app.controller("loginCtrl", function ($scope,$location, dataService) { $scope.new = {}; $scope.loginInput = function () { for ( i = 0; i < $scope.myData.length ; i++){ if ( angular.equals($scope.new.name , $scope.myData[i].name) && angular.equals($scope.new.email , $scope.myData[i].email) ){ $scope.store = $scope.new; } } if ( $scope.store){ $location.path("/emp"); } else { alert("Invalid Data!"); } }; }); /*app.controller('myCtrl1', function($scope,dataService,$location) { dataService.myFun().then(function (response) { $scope.myData = response.data.myData; }); $scope.removeInput = function (index) { $scope.myData.splice(index,1); }; $scope.editInput= function (index) { dataService.temp = index; $location.path('/edit'); }; /!*dataService.temp2 = $scope.myData.gender; dataService.temp3 = $scope.myData.name; dataService.temp4 = $scope.myData.email; dataService.temp5 = $scope.myData.city; *!/ });*/
59913e8ae963e982afb4a4bfbe67ef07a3407056
[ "JavaScript" ]
1
JavaScript
Dwipgandhi/UserDashboard
4f802f7f2998d989fe82b53c7a574288b481f1cb
77f5d9b64b727fadb34ba0e17ac5b609b4a976e8
refs/heads/master
<repo_name>Osolotkin/DBS<file_sep>/src/Main.java public class Main { private static final Database database = new Database(); private static final Menu mainMenu = new Menu(); public static void main(String[] args) { if (Config.load() == 1) { Utils.writeError("Could not load config from file!"); } // connecting to the database if (database.connect() == 1) { Utils.writeError("Could not connect to the data base"); return; } else { if (Config.VERBOSE) { Utils.writeInfo("Database connection was successful"); } } /* main menu structure or something like that - select table - show table - insert row - delete row - delete - show rows - return - find - return - change pet owner - print all pets treatments, just info - print all pets procedures with all doctors - print receipt - how many treatments has each pet (SELECT inside SELECT) - print how many different drugs are used in each procedure in specific interval (SELECT inside FROM) - print procedures that have price above average or lower (SELECT inside WHERE) - print hwo many pets have each pet owner (usage of GROUP BY) - print all doctors that hasn't participated in any treatment case (set operation) - print doctors names that have healing the pet (LEFT JOIN) - exit */ MExecution selectTable = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equals(HELP)) { writeHelp( "Selecting table specified by name.", new String[] { "name", "name of the table, names has to be spaceless." } ); return; } if (!database.existTable(args[0])) { Utils.writeError("Cannot find table: " + args[0]); return; } final String selectedTable = args[0]; System.out.println(); System.out.println("Selected table: " + selectedTable); Menu subMenu = new Menu(); MExecution showTable = new MExecution() { public void execute(String args[]) { boolean isNull = args == null; if (!isNull && args[0].equals("help")) { writeHelp( "Displaying top rows of selected table.", new String[] { "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.renderTable( selectedTable, (!isNull && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (!isNull && args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; subMenu.addItem("Show table", showTable); MExecution FindRows = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; final String[][] colInfo = database.getColNamesAndTypes(selectedTable); if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Finds rows by given arguments." + Utils.NEW_LINE + "Write in such format: " + Utils.strarr2str(colInfo[0]) + Utils.NEW_LINE + "To skip not needed cols use " + Config.SKIP_CHAR, null ); return; } args = Utils.fillTheLength(args, colInfo[0].length,Character.toString(Config.SKIP_CHAR)); String[][] argsToSearch = Utils.pickNotEmptyPairs(new String[][] { colInfo[0], args, colInfo[1] }, Config.SKIP_CHAR); String[][] rows = database.getRows(selectedTable, argsToSearch); database.renderRows(rows, colInfo[0], (args.length > colInfo[0].length) ? Utils.str2int(args[colInfo[0].length]) : Config.DEFAULT_COLUMN_WIDTH); } }; subMenu.addItem("Find rows", FindRows); MExecution insertRow = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { final String[] colNames = database.getColNames(selectedTable); writeHelp( "Inserts row into selected table." + Utils.NEW_LINE + "Write in such format: " + Utils.strarr2str(colNames) + Utils.NEW_LINE + "To skip not needed cols use " + Config.SKIP_CHAR, null ); return; } final String[][] colInfo = database.getColNamesAndTypes(selectedTable); args = Utils.fillTheLength(args, colInfo[0].length,Character.toString(Config.SKIP_CHAR)); String[][] tmp = Utils.pickNotEmptyPairs(new String[][] { colInfo[0], args, colInfo[1] }, Config.SKIP_CHAR); if (database.insertRow(selectedTable, tmp) == 1) { Utils.writeError("Could not insert row!"); return; } Utils.writeInfo("Row was successfully inserted!"); } }; subMenu.addItem("Insert row", insertRow); MExecution deleteRow = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { final String[] colNames = database.getColNames(selectedTable); writeHelp( "Deletes rows from selected table." + Utils.NEW_LINE + "Write in such format: " + Utils.strarr2str(colNames) + Utils.NEW_LINE + "To skip not needed cols use " + Config.SKIP_CHAR, null ); return; } final String[][] colInfo = database.getColNamesAndTypes(selectedTable); args = Utils.fillTheLength(args, colInfo[0].length, Character.toString(Config.SKIP_CHAR)); String[][] tmp = Utils.pickNotEmptyPairs(new String[][] { colInfo[0], args, colInfo[1] }, Config.SKIP_CHAR); String[][] rows; if ((rows = database.getRows(selectedTable, tmp)) == null) { Utils.writeError("Could not delete row!"); return; } Menu deleteMenu = new Menu(); System.out.println("Do you really want to delete " + ((rows.length > 1) ? rows.length + " rows" : "row") + "?"); MExecution delete = new MExecution() { public void execute(String[] args) { if (database.deleteRows(selectedTable, tmp) != 0) { Utils.writeError("Could not delete row!"); return; } Utils.writeInfo(((rows.length > 1) ? rows.length + " rows" : "row") + " was successfully deleted!"); } }; deleteMenu.addItem("Delete", delete); MExecution show = new MExecution() { public void execute(String[] args) { database.renderRows(rows, colInfo[0], (args != null && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_COLUMN_WIDTH); } }; deleteMenu.addItem("Show rows", show); MExecution goBack = new MExecution() { public void execute(String[] args) { } }; deleteMenu.addItem("Return", goBack); while (true) { deleteMenu.render(); int choice = deleteMenu.checkForInput(); if (choice == 3 || choice == 1) return; } } }; subMenu.addItem("Delete row", deleteRow); MExecution returnBack = new MExecution() { public void execute(String[] args) { return; } }; subMenu.addItem("Return", returnBack); while (true) { subMenu.render(); if (subMenu.checkForInput() == 5) return; } } }; mainMenu.addItem("Select table", selectTable); MExecution changePetOwner = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Changes pet owner.", new String[] { "pet id", "necessary, integer value, if not converted to zero, determines id of the pet you want to process action", "new pet owner id", "necessary, integer value, if not converted to zero, determines new owner of the selected pet" } ); return; } if (args.length < 2) { Utils.writeError("Not enough number of params." + Utils.NEW_LINE + "This function has to have two params: pet_id and owner_id!"); return; } database.changePetOwner(Utils.str2int(args[0]), Utils.str2int(args[1])); } }; mainMenu.addItem("Change Pet Owner", changePetOwner); MExecution printTreatments = new MExecution() { public void execute(String[] args) { boolean isNull = args == null; if (!isNull && args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints treatment cases", new String[] { "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printTreatmentCases( (!isNull && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (!isNull && args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("Print treatment cases", printTreatments); MExecution printProceduresInfo = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints procedures info of the selected pet by id.", new String[] { "pet id", "necessary, integer value, if not converted to zero, determines id of the pet which procedures info will be shown.", "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printProceuresInfo( Utils.str2int(args[0]), (args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_TOP_ROWS, (args.length > 2) ? Utils.str2int(args[2]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("Print procedures info", printProceduresInfo); MExecution printReceipt = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints receipt for specific pet owner.", new String[] { "pet owner id", "necessary, integer value, if not converted to zero, determines id of the pet owner." } ); return; } database.printReceipt(Utils.str2int(args[0])); } }; mainMenu.addItem("Print receipt", printReceipt); MExecution SELECTinsideSELECT = new MExecution() { public void execute(String[] args) { boolean isNull = args == null; if (!isNull && args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints how many treatments has each pet.", new String[] { "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printPetTreatmentCount( (!isNull && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (!isNull && args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(SELECT inside SELECT)", SELECTinsideSELECT); MExecution SELECTinsideFROM = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints drug count of each procedure on specific interval.", new String[] { "bottom bound", "necessary, integer value, if not converted to zero, specifies bottom bound of the interval.", "upper bound", "unnecessary, integer value, if not converted to zero, specifies upper bound of the interval.", "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printProceduresDrugCountInt( (args.length > 0) ? Utils.str2int(args[0]) : 0, (args.length > 1) ? Utils.str2int(args[1]) : Integer.MAX_VALUE, (args.length > 2) ? Utils.str2int(args[2]) : Config.DEFAULT_TOP_ROWS, (args.length > 3) ? Utils.str2int(args[3]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(SELECT inside FROM)", SELECTinsideFROM); MExecution SELECTinsideWHERE = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints procedures that have price above average or below.", new String[] { "aver side", "necessary, 1 for above, something other for below", "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printProceduresAverPrice( args[0].equalsIgnoreCase("1"), (args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_TOP_ROWS, (args.length > 2) ? Utils.str2int(args[2]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(SELECT inside WHERE)", SELECTinsideWHERE); MExecution GROUPBY = new MExecution() { public void execute(String[] args) { boolean isNull = args == null; if (!isNull && args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints hwo many pets have each pet owner.", new String[] { "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printPetOwnersPetCount( (!isNull && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (!isNull && args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(GROUP BY)", GROUPBY); MExecution setOperation = new MExecution() { public void execute(String[] args) { boolean isNull = args == null; if (!isNull && args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints all doctors that hasn't participated in any treatment case.", new String[] { "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printNoActionDoctors( (!isNull && args.length > 0) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (!isNull && args.length > 1) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(set operation)", setOperation); MExecution LEFTJOIN = new MExecution() { public void execute(String[] args) { if (nullCheck(args)) return; if (args[0].equalsIgnoreCase(HELP)) { writeHelp( "Prints doctors names that have healing the pet", new String[] { "pet id", "necessary, integer value, if not converted to zero, determines id of the pet.", "top rows", "unnecessary, integer value, if not converted to zero, specifies number of rows that will be rendered, if given number is higher than number of rows in selected table, draws em all, default value: " + Config.DEFAULT_TOP_ROWS, "col width", "unnecessary, integer value, if not converted to zero, specifies width of each column in chars, min width is 3, some fancy spaces and other stuff, that has nothing to do with table value, but decoration, does not count, default value: " + Config.DEFAULT_COLUMN_WIDTH } ); return; } database.printDoctorsForThePet( Utils.str2int(args[0]), (args.length > 1) ? Utils.str2int(args[0]) : Config.DEFAULT_TOP_ROWS, (args.length > 2) ? Utils.str2int(args[1]) : Config.DEFAULT_COLUMN_WIDTH ); } }; mainMenu.addItem("(LEFT JOIN)", LEFTJOIN); MExecution exit = new MExecution() { public void execute(String[] args) { } }; mainMenu.addItem("Exit", exit); while(true) { mainMenu.render(); if (mainMenu.checkForInput() == 12) break; } } } <file_sep>/InsertTestData.sql -- pet owners INSERT INTO pet_owner (first_name, last_name) VALUES ('Segal', 'Telesphore'), ('Dominique', 'Traverse'), ('Tamara', 'Simmons'), ('Humphrey', 'Jenkins'), ('Efim', 'Vasiliev'), ('Zanuda', 'Svatagra'), ('Roadin', 'House'), ('Bogdan', 'Vavil'), ('Iluka', 'Madinsk'), ('Krabislav', 'Ionasii'); -- pets INSERT INTO pet (name, type, owner_id) VALUES ('Ramona', 'cat', 10), ('Waffle', 'hare', 2), ('Stinker', 'dog', 3), ('Harper', 'parrot', 5), ('Pandora', 'dog', 6), ('Clifford', 'pig', 4), ('Sabbath', 'turtle', 9), ('Rasputin', 'cat', 8), ('Ramona', 'dog', 6), ('Malloc', 'rabbit', 7), ('Ferrbi', 'cat', 1), ('Lizzina', 'pig', 8), ('Kolaii', 'rabbit', 9); -- doctors INSERT INTO doctor (first_name, last_name) VALUES ('Gwynn', 'Nevitt'), ('Baha', 'Demir'), ('Hasnaa', 'Okonjo'), ('Tercero', 'Bracero'), ('Vikentiy', 'Popo'), ('Yao', 'Qingshan'), ('Sun', 'Jae-Hwa'), ('Yamagata', 'Torvald'), ('Emlin', 'Weiner'), ('Federigo', 'Ferrari'); -- drugs INSERT INTO drug (name, description, quantity) VALUES ( 'NIACOR', 'Each NIACOR® (niacin tablets) Tablet, for oral administration, contains 500 mg of nicotinic acid. In addition, each tablet contains the following inactive ingredients: croscarmellose sodium, hydrogenated vegetable oil, magnesium stearate and microcrystalline cellulose.', 10 ), ( 'LODOSYN', 'Lodosyn (carbidopa) is an inhibitor of aromatic amino acid decarboxylation used with levodopa to treat the stiffness, tremors, spasms, and poor muscle control of Parkinson''s disease. Lodosyn and levodopa are also used to treat the same muscular conditions when caused by drugs such as chlorpromazine, fluphenazine, perphenazine, and others. Levodopa is turned into dopamine in the body.', 13 ), ( 'COGNEX', 'Tacrine hydrochloride is a white solid and is freely soluble in distilled water, 0.1N hydrochloric acid, acetate buffer (pH 4.0), phosphate buffer (pH 7.0 to 7.4), methanol, dimethylsulfoxide (DMSO), ethanol, and propylene glycol. The compound is sparingly soluble in linoleic acid and PEG 400.', 14 ), ( 'QINLOCK', 'Ripretinib is used to treat tumors of the stomach and intestines. Ripretinib is for use in adults who have already been treated with at least 3 other cancer medicines. Ripretinib may also be used for purposes not listed in this medication guide.', 88 ), ( 'VABOMERE', 'Vabomere (meropenem and vaborbactam) for injection is a combination of a penem antibacterial and a beta-lactamase inhibitor, indicated for the treatment of patients 18 years and older with complicated urinary tract infections (cUTI) including pyelonephritis caused by designated susceptible bacteria.', 76 ), ( 'ACCOLATE', 'Accolate is a prescription medicine used to treat the symptoms of Asthma. Accolate may be used alone or with other medications. Accolate belongs to a class of drugs called Leukotriene Receptor Antagonists. It is not known if Accolate is safe and effective in children younger than 5 years of age.', 66 ), ( 'RECLAST', 'Reclast is used to treat osteoporosis caused by menopause, steroid use, or gonadal failure. This medicine is for use when you have a high risk of bone fracture due to osteoporosis. Reclast is also used to treat Paget''s disease of bone.', 9 ), ( 'KYNMOBI', 'Kynmobi is a prescription medicine used to treat short-term (acute), intermittent “off” episodes in people with Parkinson’s disease (PD). It is not known if Kynmobi is safe and effective in children.', 17 ), ( 'CABLIVI', 'Caplacizumab is used to treat acquired thrombotic thrombocytopenic purpura (aTTP) in adults. Caplacizumab is given together with immunosuppressant medication and plasma exchange (transfusion). Caplacizumab may also be used for purposes not listed in this medication guide.', 2 ), ( 'PANCRECARB', 'Pancrelipase is a combination of three enzymes (proteins): lipase, protease, and amylase. These enzymes are normally produced by the pancreas and are important in the digestion of fats, proteins, and sugars.', 8 ); -- procedures INSERT INTO [procedure] (name, description, duration, price) VALUES ( 'Super Duper One', 'Doing some magical stuff to make pet feel allright', 3600000, 66600 ), ( 'Misdoubt Torque', 'Doing some magical stuff to make pet feel allright', 4200000, 148900 ), ( '<NAME>', 'Doing some magical stuff to make pet feel allright', 1800000, 1112300 ), ( 'Aberrational', 'Doing some magical stuff to make pet feel allright', 9600000, 2323100 ), ( 'Tantalizingly', 'Doing some magical stuff to make pet feel allright', 4300000, 222300 ), ( 'Introvenient', 'Doing some magical stuff to make pet feel allright', 5600000, 323200 ), ( 'Nepenthes', 'Doing some magical stuff to make pet feel allright', 7800000, 333200 ), ( '<NAME>', 'Doing some magical stuff to make pet feel allright', 1100000, 66600 ), ( '<NAME>', 'Doing some magical stuff to make pet feel allright', 200000, 66600 ), ( 'Therapeutaelig', 'Doing some magical stuff to make pet feel allright', 2300000, 66600 ), ( '<NAME>', 'Doing some magical stuff to make pet feel allright', 9900000, 66600 ); -- procedures drugs INSERT INTO procedure_drug (procedure_id, drug_id) VALUES (1, 2), (1, 3), (2, 2), (2, 1), (2, 7), (3, 8), (4, 10), (4, 9), (6, 5), (7, 1), (8, 3), (8, 5), (8, 7), (8, 9), (9, 2), (10, 10), (10, 9); -- treatments INSERT INTO treatment (pet_id, doctor_id, procedure_id) VALUES (1, 2, 1), (1, 1, 2), (2, 4, 3), (2, 6, 3), (2, 8, 3), (3, 9, 10), (4, 9, 1), (4, 9, 2), (4, 5, 5), (4, 8, 7), (5, 9, 9), (5, 1, 2), (6, 7, 5), (7, 8, 4), (8, 8, 3), (8, 8, 5), (9, 9, 1), (10, 9, 3), (11, 3, 4), (12, 2, 7), (12, 2, 3), (13, 1, 2); <file_sep>/src/Utils.java public class Utils { public static final char NEW_LINE = '\n'; public static final char TAB = '\t'; public static final String OS = System.getProperty("os.name"); public static void writeError(String str) { System.out.print(Colors.YELLOW); System.out.println(str + NEW_LINE); System.out.print(Colors.RESET); } public static void writeInfo(String str) { System.out.print(Colors.GREEN); System.out.println(str + NEW_LINE); System.out.print(Colors.RESET); } public static int str2int(String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return 0; } } public static double str2double(String str) { try { if (str == null) return 0; return Double.parseDouble(str); } catch (NumberFormatException e) { return 0; } } public static String strarr2str(String str[]) { return strarr2str(str, ' '); } public static String strarr2str(String str[], char delimiter) { return strarr2str(str, delimiter, Character.MIN_VALUE); } public static String strarr2str(String str[], char delimiter, char wrapper) { if (str.length < 1) return null; StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < str.length - 1; i++) { sb.append(wrapper + str[i] + wrapper + delimiter); } sb.append(str[i]); return sb.toString(); } // let we have two arrays of same length A and B, function connect A[n] with B[n], for n > 0 && n < A.length, // using delimiter in such way - A[n] + delimiterAB[n] + B[n] = C[n], and then connect each element of C to one String // with another delimiterC public static String strarrs2str(String A[], String B[], String delimiterAB[], String delimiterC) { return strarrs2str(A, B, delimiterAB, delimiterC, new char[A.length], new char[A.length]); } public static String strarrs2str(String A[], String B[], String delimiterAB[], String delimiterC, char[] wrapperA, char[] wrapperB) { if (A.length < 1 || A.length > B.length) return null; if (A.length > wrapperA.length || A.length > wrapperB.length) return null; StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < A.length - 1; i++) { sb.append(wrapperA[i] + A[i] + wrapperA[i] + delimiterAB[i] + wrapperB[i] + B[i] + wrapperB[i] + delimiterC); } sb.append(wrapperA[i] + A[i] + wrapperA[i] + delimiterAB[i] + wrapperB[i] + B[i] + wrapperB[i]); return sb.toString(); } // again copy paste, but i guess its better than creating array if not needed public static String strarrs2str(String A[], String B[], String delimiterAB, String delimiterC) { return strarrs2str(A, B, delimiterAB, delimiterC, new char[A.length], new char[A.length]); } public static String strarrs2str(String A[], String B[], String delimiterAB, String delimiterC, char[] wrapperA, char[] wrapperB) { if (A.length < 1 || A.length > B.length) return null; if (A.length > wrapperA.length || A.length > wrapperB.length) return null; StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < A.length - 1; i++) { sb.append(wrapperA[i] + A[i] + wrapperA[i] + delimiterAB + wrapperB[i] + B[i] + wrapperB[i] + delimiterC); } sb.append(wrapperA[i] + A[i] + wrapperA[i] + delimiterAB + wrapperB[i] + B[i] + wrapperB[i]); return sb.toString(); } public static String[][] pickNotEmptyPairs(String[][] str, char emptyChar) { if (str.length < 2) return null; for (int i = 1; i < str.length; i++) { if (str[0].length > str[i].length) return null; } String[] pairs = new String[str.length * str[0].length]; int k = 0; for (int i = 0; i < str[0].length; i++) { boolean isEmpty = false; for (int j = 0; j < str.length; j++) { isEmpty = isEmpty || str[j][i].length() == 1 && str[j][i].charAt(0) == emptyChar; } if (isEmpty) continue; for (int j = 0; j < str.length; j++) { pairs[k] = str[j][i]; k++; } } String[][] pairsFinal = new String[str.length][k / str.length]; for (int i = 0; i < pairsFinal[0].length; i++) { for (int j = 0; j < str.length; j++) { pairsFinal[j][i] = pairs[str.length * i + j]; } } return pairsFinal; } public static String[] fillTheLength(String[] arr, int length, String valToFill) { if (arr.length >= length || length < 1) return arr; String[] newArr = new String[length]; for (int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } for (int i = arr.length; i < newArr.length; i++) { newArr[i] = valToFill; } return newArr; } public class Colors { // Reset public static final String RESET = "\033[0m"; // Text Reset public static final String GREEN = "\033[92m"; // GREEN public static final String YELLOW = "\033[93m"; // YELLOW } }
cbcf0819b0abd97c4f6edf78a48804c25db3468b
[ "Java", "SQL" ]
3
Java
Osolotkin/DBS
0515f7f2d1a032c405b18111a6139e6c8f995aba
f7055ab0f9f451c1044c0662555d6ab2c99e5632
refs/heads/master
<file_sep>import React, { Component } from 'react'; class PizzaForm extends Component { state = { pizza: this.props.pizza, topping: this.props.pizza.topping, size: this.props.pizza.size, vegetarian: this.props.pizza.vegetarian } componentDidUpdate(prevProps) { if (this.props.pizza !== prevProps.pizza) { this.updatePizza(this.props) } } updatePizza = e => { this.setState({ pizza: e.pizza, topping: e.pizza.topping, size: e.pizza.size, vegetarian: e.pizza.vegetarian }) } handleToppingChange = e => { this.setState({ topping: e.target.value }) } handleSizeChange = e => { this.setState({ size: e.target.value }) } handleVegetarianChange = e => { this.state.vegetarian ? this.setState({ vegetarian: false }) : this.setState({ vegetarian: true }) } render() { return( <div className="form-row"> <div className="col-5"> <input onChange={this.handleToppingChange}type="text" className="form-control" placeholder="Pizza Topping" value={this.state.topping}/> </div> <div className="col"> <select onChange={this.handleSizeChange} value={this.state.size} className="form-control"> <option value="Small">Small</option> <option value="Medium">Medium</option> <option value="Large">Large</option> </select> </div> <div className="col"> <div className="form-check"> <input onChange={this.handleVegetarianChange} className="form-check-input" type="radio" value="Vegetarian" checked={this.state.vegetarian}/> <label className="form-check-label"> Vegetarian </label> </div> <div className="form-check"> <input onChange={this.handleVegetarianChange} className="form-check-input" type="radio" value="Not Vegetarian" checked={!this.state.vegetarian}/> <label className="form-check-label"> Not Vegetarian </label> </div> </div> <div className="col"> <button type="submit" className="btn btn-success" onClick={()=> this.props.submitEdit(this.state)}>Submit</button> </div> </div> ) } } export default PizzaForm <file_sep>import React, { Component, Fragment } from 'react'; import Header from './components/Header' import PizzaForm from './components/PizzaForm' import PizzaList from './containers/PizzaList' class App extends Component { state = { currentPizza: null } updateCurrentPizza = e => { this.setState({currentPizza: e}) } editPizza = e => { this.setState({currentPizza: e}) } submitEdit = e => { console.log(e) if( e.pizza.id !== -1 ){ this.patch(e) } else { console.log("create") } } patch = (e) => { console.log(e) fetch(`http://localhost:3000/pizzas/${e.pizza.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify({ topping: e.topping, size: e.size, vegetarian: e.vegetarian }) }) .then(res => res.json()) .then(data => { console.log(data) this.updateCurrentPizza(data) }) } render() { let defaultPizza = { "id": -1, "topping": "Plain", "size": "Small", "vegetarian": true } const pizza = this.state.currentPizza || defaultPizza return ( <Fragment> <Header/> <PizzaForm editPizza={this.editPizza} pizza={pizza} submitEdit={this.submitEdit} /> <PizzaList editPizza={this.editPizza} pizza={pizza}/> </Fragment> ); } } export default App;
952a4f23592e685008a6da541aa1436532a0347f
[ "JavaScript" ]
2
JavaScript
ronaldabreu-dev/React-Pizza-nyc01-seng-ft-051120
4a8b96dc84806284c48b8ad38e4470e22a5404ba
e7dae08fa6e7fe182c3d683b838c4ea9be7931c2
refs/heads/master
<file_sep>download dataset from https://www.kaggle.com/c/kkbox-music-recommendation-challenge and put them here <file_sep>out #coding:utf-8 # train.py from scipy import stats from prepro_and_train import * import numpy as np import pandas as pd from sklearn.feature_extraction import FeatureHasher from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from tqdm import tqdm import xgboost as xgb from tempfile import mkdtemp from joblib import Memory from scipy.sparse import csc_matrix,csr_matrix import xgboost as xgb from sklearn.decomposition import TruncatedSVD import math as mt import csv from sparsesvd import sparsesvd import joblib import os import langid from sklearn.metrics.pairwise import pairwise_distances from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import KFold from fastFM import sgd import os import tqdm X_merged,X_test_merged,y = None,None,None if os.path.isfile('../out/dump/featuresv2.dump'): X_merged, X_test_merged,y = joblib.load('../out/dump/featuresv2.dump') else: X,y,X_test = None,None,None if os.path.isfile("../out/dump/preprocessing008.dump"): X,y,X_test = joblib.load("../out/dump/preprocessing008.dump") else: X,y,X_test = preprocessing008() joblib.dump((X,y,X_test),filename="../out/dump/preprocessing008.dump",compress=3) contexttrain,contexttest = None,None if os.path.isfile("../out/dump/preprocessing_source_type_source_screen_name_source_type.dump"): contexttrain, contexttest = joblib.load("../out/dump/preprocessing_source_type_source_screen_name_source_type.dump") else: contexttrain, contexttest = preprocessing_source_type_source_screen_name_source_type() joblib.dump((contexttrain,contexttest ),filename="../out/dump/preprocessing_source_type_source_screen_name_source_type.dump",compress=3) contexttrain.drop('msno',axis=1,inplace=True) contexttest.drop('msno',axis=1,inplace=True) contexttrain.fillna(0,inplace=True) contexttest.fillna(0,inplace=True) #------------------------- wordembedding = None if os.path.isfile("../out/dump/mpimatrix_galc_svdfeat15allinone.dump"): wordembedding = joblib.load("../out/dump/mpimatrix_galc_svdfeat15allinone.dump") else: pass #------------------------- #preprocessing_text_apply textone,texttwo = None,None if os.path.isfile("../out/dump/preprocessing_text.dump"): textone,texttwo = joblib.load("../out/dump/preprocessing_text.dump") else: textone,texttwo = preprocessing_text() joblib.dump((textone,texttwo),filename="../out/dump/preprocessing_text.dump",compress=3) textone.fillna(-1,inplace=True) texttwo.fillna(-1,inplace=True) latent = 30 name = "preprocessing005_dropdup_%d" % latent U, V, train, test, train_u, test_u, train_v, test_v = None, None, None, None, None, None, None, None if os.path.isfile("../out/dump/%s.dump" % name): U, V, train, test, train_u, test_u, train_v, test_v = joblib.load("../out/dump/%s.dump" % name) else: U, V, train, test, train_u, test_u, train_v, test_v = preprocessing005_dropdup(latent) joblib.dump((U, V, train, test, train_u, test_u, train_v, test_v), filename="../out/dump/%s.dump" % name, compress=3) X_merged = pd.concat((X, textone, pd.DataFrame(train_u,columns=["SVD_user_%d" % i for i in range(latent)]), pd.DataFrame(train_v, columns=["SVD_item_%d" % i for i in range(latent)]), pd.DataFrame((train_u * train_v), columns=['SVD_useritem_dot_%d' % i for i in range(30)]), pd.DataFrame((train_u * train_v).sum(axis=1),columns=['SVD_useritem_dot']), contexttrain) ,axis=1) X_test_merged = pd.concat((X_test, texttwo, pd.DataFrame(test_u,columns=["SVD_user_%d" % i for i in range(latent)]), pd.DataFrame(test_v, columns=["SVD_item_%d" % i for i in range(latent)]), pd.DataFrame((test_u * test_v), columns=['SVD_useritem_dot_%d' % i for i in range(30)]) ,pd.DataFrame((test_u * test_v).sum(axis=1),columns=['SVD_useritem_dot']), contexttest) ,axis=1) joblib.dump((X_merged, X_test_merged,y),filename='../out/dump/featuresv2.dump',compress=3) train = pd.read_csv('../data/train.csv') test = pd.read_csv('../data/test.csv') wordembedding = None if os.path.isfile("../out/dump/mpimatrix_galc_svdfeat15allinone.dump"): wordembedding = joblib.load("../out/dump/mpimatrix_galc_svdfeat15allinone.dump") else: pass wordembedding.reset_index(drop=True,inplace=True) wordembedding.columns = ['wordembedding_%d' % i for i in range(len(wordembedding.columns))] X_merged = pd.concat((X_merged,wordembedding.iloc[:len(X_merged)]),axis=1) X_test_merged = pd.concat((X_test_merged,wordembedding.iloc[len(X_merged):].reset_index(drop=True)),axis=1) print X_merged print X_test_merged for newsimi in ['lyricist_split', 'composer_split','artist_name_split' ,'genre_split']: genre_simi = pd.read_csv("../out/simi/%s_dot_simi.csv_md" % newsimi,header=None) genre_simi.fillna(0,inplace=True) X_merged["%s_dot_simi" % newsimi] = genre_simi[0].values[:len(X_merged)] X_test_merged["%s_dot_simi" % newsimi] = genre_simi[0].values[len(X_merged):] genre_svddot = pd.read_csv("../out/simi/artist_name_svddot.csv",header=None) X_merged["%s_svddot" % newsimi] = genre_svddot[0].values[:len(X_merged)] X_test_merged["%s_svddot" % newsimi] = genre_svddot[0].values[len(X_merged):] for feature in ['source_system_tab','source_type','source_screen_name']: dotsimi = pd.read_csv("../out/simi/%s_dot_simi.csv" % feature, header=None) X_merged["%s_svddot" % feature] = dotsimi[0].values[:len(X_merged)] X_test_merged["%s_svddot" % feature] = dotsimi[0].values[len(X_merged):] cfscore = pd.read_csv('../out/simi/cf_cos_top100.csv',header=None) X_merged['cfcos100'] = cfscore[0].values[:len(X_merged)] X_test_merged['cfcos100'] = cfscore[0].values[len(X_merged):] languagesimi = pd.read_csv('../out/simi/language_dot_simi.csv',header=None) X_merged['languagesimi'] = languagesimi[0].values[:len(X_merged)] X_test_merged['languagesimi'] = languagesimi[0].values[len(X_merged):] # drop song_count features different distribution selected=[] X_merged.drop(['song_count'],axis=1,inplace=True) X_test_merged.drop(['song_count'],axis=1,inplace=True) #X_merged.drop(['msno','song_id'],axis=1,inplace=True) #X_test_merged.drop(['msno','song_id'],axis=1,inplace=True) t # delete duplicate except target == 1 print "len train before", len(X_merged) inertest = test inertrain = train inerdata = pd.concat((inertrain[['msno', 'song_id']], inertest[['msno', 'song_id']])) dup = inerdata.duplicated(subset=['msno', 'song_id'], keep='last') dup = np.logical_not(dup.values) targetone = (inertrain['target'] == 1) X_merged['target']=y X_merged = X_merged[(dup[:len(inertrain)] | targetone ) ] print "len train after ", len(X_merged),len(y) print "len drop old user ",len(X_merged) y = X_merged['target'] X_merged.drop('target',axis=1,inplace=True) X_merged.reset_index(drop=True,inplace=True) y.reset_index(drop=True,inplace=True) X_merged.reset_index(drop=True,inplace=True) # X_merged['target'] = y # # X_merged = X_merged.sample(frac=0.1,random_state=111) # # y = X_merged['target'] # X_merged.drop('target',axis=1,inplace=True) # X_merged.reset_index(drop=True,inplace=True) # y.reset_index(drop=True,inplace=True) #X_merged['target'] = y # registration_init_time = train['registration_init_time'].cummax() # train['timestamp'] = registration_init_time # train.loc[train[train['timestamp']<20161201].index,'timestamp'] = 20161201 # X_merged['timestamp'] = train['timestamp'] # X_merged = X_merged[X_merged['timestamp'] >= 20170101] # X_merged.drop('timestamp',axis=1,inplace=True) # X_merged.reset_index(drop=True,inplace=True) #y = X_merged['target'] #X_merged.drop('target',axis=1,inplace=True) submit_cv = None cv=0 dump_name = '12.17add4_dot_simi_addgenrediffsimi_cfcos100score_language_dotsimi_artist_name_svddot_threesimi' skf = StratifiedKFold(n_splits=10, random_state=253, shuffle=True) for train_index, valid_index in skf.split(X_merged, y): cv += 1 X_train, X_valid = X_merged.iloc[train_index], X_merged.iloc[valid_index] y_train, y_valid = y.iloc[train_index], y.iloc[valid_index] submit, validpred, model = lgbm2(X_train, X_valid, y_train, y_valid, X_test_merged, test['id'].values, params={'learning_rate': 0.1, "application": 'binary', "max_depth": 15, 'num_leaves': 2 ** 8, 'verbosity': 0, 'metric': 'auc', 'num_threads': 50, 'colsample_bytree': 0.9, 'subsample': 0.9}, num_boost_round=3100, early_stopping_rounds=10) if submit_cv is None: submit_cv = submit else: submit_cv['target'] += submit['target'] submit.to_csv('../out/%s_subcv_%d.csv.gz' % (dump_name, cv), compression='gzip', index=False, float_format='%.8f') validpred.to_csv('../out/%s_validcv_%d.csv.gz' % (dump_name, cv), index=False, float_format='%.8f') joblib.dump(model,filename='../out/%s_%d.model.dump' % ( dump_name, cv) ) <file_sep># WSDN_18_KKBOX_music_recommend ## description That is the code for 6th solution at Kaggle KKBox music recommendation challenge [here](https://www.kaggle.com/c/kkbox-music-recommendation-challenge/discussion/45999). Also, that is the code corrsponding to paper "KKbox’s Music Recommendation Challenge Solution with Feature engineering" [here](http://wsdm-cup-2018.kkbox.events/pdf/WSDM_KKboxs_Music_Recommendation_Challenge_6th_Solution.pdf). Detail are shown in "KKbox’s Music Recommendation Challenge Solution with Feature engineering". Ensamble part is not included here. ### user\_song\_simi\_contextbase.py & user\_song\_simi\_songbase.py That is the code for calculating similarity of user and song by different features. This part uses parallel from Joblib to speed up. ### user\_artist\_svd.py That is the code for SVD represenation of user and artist by sparsesvd at [here](https://pypi.org/project/sparsesvd/). ### prepro\_and\_train.py That is the code of other basic preprocessing, feature engineering and classification model. ### cfscore.py That is the code of calculating Collaborative Filtering score for user and song. ### train.py Training and dumping the model and results in ../out/ ## Workflow 1. Download dataset from [here](https://www.kaggle.com/c/kkbox-music-recommendation-challenge/) and put it in /data/ 2. run user\_song\_simi\_contextbase.py user\_song\_simi\_songbase.py user\_artist\_svd.py to generate similarity and SVD features 3. run train.py to generate other features and train a classification model. <file_sep># coding=utf-8 import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from tqdm import tqdm import xgboost as xgb from tempfile import mkdtemp from joblib import Memory from scipy.sparse import csc_matrix, csr_matrix, lil_matrix import math as mt import csv from sparsesvd import sparsesvd import joblib import os import langid from sklearn.metrics.pairwise import pairwise_distances from sklearn.model_selection import StratifiedKFold from fastFM import sgd import sys import numpy as np from itertools import product import scipy.sparse as sparse import scipy from multiprocessing import Pool def uifeat_generate(transection): data = transection user_itemfeat = data.groupby('msno')[['msno_le']].first() print 'genreids...' user_itemfeat['genre_ids'] = data.groupby('msno')['genre_ids'].agg(lambda x: "|".join(x)) print 'artist...' user_itemfeat['artist_name'] = data.groupby('msno')['artist_name'].agg(lambda x: "|".join(x)) print 'lyricist...' user_itemfeat['lyricist'] = data.groupby('msno')['lyricist'].agg(lambda x: "|".join(x)) print 'composer...' user_itemfeat['composer'] = data.groupby('msno')['composer'].agg(lambda x: "|".join(x)) print 'genreids...' user_itemfeat['genre_split'] = user_itemfeat.genre_ids.str.split(r'[;|/\\,+、&]+') print 'artist_name...' user_itemfeat['artist_name_split'] = user_itemfeat.artist_name.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') print 'lyricist...' user_itemfeat['lyricist_split'] = user_itemfeat.lyricist.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') print 'composer...' user_itemfeat['composer_split'] = user_itemfeat.composer.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') print "user reset index" user_itemfeat.reset_index(drop=False, inplace=True) return user_itemfeat def songfeat_generate(subsongs): print "song sink" songs = subsongs.copy() songs['genre_ids'].fillna('others_genre', inplace=True) songs['artist_name'].fillna('other_artist', inplace=True) songs['composer'].fillna('other_composer', inplace=True) songs['lyricist'].fillna('other_lyricist', inplace=True) songs['genre_split'] = songs.genre_ids.str.split(r'[;|/\\,+、&]+') print 'artist_name...' songs['artist_name_split'] = songs.artist_name.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') print 'lyricist...' songs['lyricist_split'] = songs.lyricist.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') print 'composer...' songs['composer_split'] = songs.composer.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') return songs def useritemfeat_vec(userfeat, songfeat, urows_matrix=None, srows_matrix=None, features='genre_split'): # for features in ['genre_split', 'lyricist_split', 'composer_split','artist_name_split' ]: le = LabelEncoder() user_itemfeat = userfeat songs = songfeat print 'vec for item feat' index = [] value = [] farray = songs[['song_id_le', features]].values for i in range(len(farray)): uid = farray[i][0] val = farray[i][1] value.extend(val) index.extend([uid] * len(val)) le.fit(value) item_genreid_le = le.transform(value) shapeu = (userfeat['msno_le'].max() + 1, item_genreid_le.max() + 1) shapes = (songfeat['song_id_le'].max() + 1, item_genreid_le.max() + 1) if urows_matrix is not None: shapeu = (urows_matrix, item_genreid_le.max() + 1) if srows_matrix is not None: shapes = (srows_matrix, item_genreid_le.max() + 1) item_genreid_matrix = csr_matrix(([1.0] * len(index), (index, item_genreid_le)), shape=shapes).tolil() print "vec for item feat done" print "vec for user feat" index = [] value = [] farray = user_itemfeat[['msno_le', features]].values for i in range(len(farray)): mid = farray[i][0] val = farray[i][1] value.extend(val) index.extend([mid] * len(val)) print 'label transform...' user_feat_le = le.transform(value) usergenre_matrix = csr_matrix(([1.0] * len(index), (index, user_feat_le)), shape=shapeu).tolil() print "done" return usergenre_matrix, item_genreid_matrix def similarity(): if __name__ == "__main__": #features = sys.argv[1] njobs = int(sys.argv[1]) print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') members = pd.read_csv(data_path + 'members.csv') for col in ['artist_name', 'composer', 'lyricist']: songs[col] = songs[col].str.replace(r'\([\s\S]+?\)', '') songs[col] = songs[col].str.replace(r'([\s\S]+?)', '') print('Data preprocessing merge and fillna and numeric encoding...') data = pd.concat((train[['msno', 'song_id', 'target']], test[['msno', 'song_id']])) data = data.merge(songs[['song_id', 'genre_ids', 'artist_name', 'composer', 'lyricist']], on='song_id', how='left') data['genre_ids'].fillna("others_genre", inplace=True) data['artist_name'].fillna('other_artist', inplace=True) data['composer'].fillna('other_composer', inplace=True) data['lyricist'].fillna('other_lyricist', inplace=True) data.ix[data[(data['composer'].str.len() > 500)].index, 'composer'] = 'other_composer' le = LabelEncoder() data['msno_le'] = msnole = le.fit_transform(data['msno']) data['song_id_le'] = songle = le.fit_transform(data['song_id']) print data['msno_le'].max() print('Data preprocessing songs...') songs.ix[songs[songs['composer'].str.len() > 500].index, 'composer'] = 'other_composer' songs = songs.merge(data[['song_id', 'song_id_le']].drop_duplicates(), on='song_id', how='right') ufeat = uifeat_generate(data) ifeat = songfeat_generate(songs) for features in [ 'lyricist_split', 'composer_split','artist_name_split' ,'genre_split']: ufeatmatrix, ifeatmatrix = useritemfeat_vec(ufeat, ifeat,features=features) def similarity_vec_njobs(input): a = ufeatmatrix[input[0]].tocsr().tocoo() b = ifeatmatrix[input[1]].tocsr().tocoo() #print "simi" a_b = a - b #print "1/3" a_b = a_b.multiply(1 / a_b.sum(axis=1)) #print "2/3" b_ = b.multiply(1 / b.sum(axis=1)) #print "3/3" cossimi = a_b.multiply(b_).sum( axis=1).A1 # / ((a_b.multiply(a_b)).sum(axis=1).A1 * (b_.multiply(b_)).sum(axis=1)).sum(axis=1).A1 #print "done" return cossimi p = Pool(njobs) para = [] for i in range(max(njobs-1,10)): para.append((data['msno_le'].values[len(data)/njobs*(i):len(data)/njobs*(i+1)] ,data['song_id_le'].values[len(data)/njobs*(i):len(data)/njobs*(i+1)])) para.append((data['msno_le'].values[len(data)/njobs*(njobs-1):] ,data['song_id_le'].values[len(data)/njobs*(njobs-1):])) print 'compute simi' simi = p.map(similarity_vec_njobs,para) simiflatten = [] for val in simi: simiflatten.extend(val) simi_pd = pd.DataFrame(simiflatten) simi_pd.to_csv('../out/simi/%s_dot_simi_clean.csv' % features,index=None) <file_sep>#features = sys.argv[1] # coding=utf-8 import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from tqdm import tqdm import xgboost as xgb from tempfile import mkdtemp from joblib import Memory from scipy.sparse import csc_matrix, csr_matrix,lil_matrix import math as mt import csv from sparsesvd import sparsesvd import joblib import os import langid from sklearn.metrics.pairwise import pairwise_distances from sklearn.model_selection import StratifiedKFold from fastFM import sgd print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') data = pd.concat((train[['msno', 'song_id', 'target','source_system_tab','source_screen_name','source_type']], test[['msno', 'song_id','source_system_tab','source_screen_name','source_type']])) data = data.merge(songs[['song_id','language', ]], on='song_id', how='left') data['language'].fillna(-1,inplace=True) data['source_system_tab'].fillna('other_source_system_tab',inplace=True) data['source_screen_name'].fillna('source_screen_name', inplace=True) data['source_type'].fillna('source_type', inplace=True) le = LabelEncoder() data['msno_le'] = msnole = le.fit_transform(data['msno']) data['song_id_le'] = songle = le.fit_transform(data['song_id']) def simi_bydump(feature): valuecount = data.groupby('msno_le')[feature].value_counts(normalize=False, dropna=False) valuecount = valuecount.unstack(level=-1).add_prefix(feature) valuecount = valuecount.reset_index(drop=False) data_valuecount = data[['msno_le']].merge(valuecount,on='msno_le',how="left") data_language = pd.get_dummies(data[feature],prefix=feature) data_valuecount.fillna(0,inplace=True) data_valuecount.drop('msno_le',axis=1,inplace=True) data_valuecount_data_language = (data_valuecount.values - data_language.values)*1.0 data_valuecount_data_language /= data_valuecount_data_language.sum(axis=1)[:,np.newaxis] langsimi = (data_valuecount_data_language * data_language.values).sum(axis=1) print pd.Series(langsimi).corr(train['target']) pd.DataFrame(langsimi).to_csv("../out/simi/%s_dot_simi.csv" % feature,index=None,header=None) for feat in ['source_system_tab','source_type','source_screen_name','language']: simi_bydump(feat)<file_sep>dump model and results here <file_sep>#coding:utf-8 # train.py import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from tqdm import tqdm import xgboost as xgb from tempfile import mkdtemp from joblib import Memory from scipy.sparse import csc_matrix,csr_matrix import xgboost as xgb from sklearn.decomposition import TruncatedSVD import math as mt import csv from sparsesvd import sparsesvd import joblib import os import langid from sklearn.metrics.pairwise import pairwise_distances from sklearn.model_selection import StratifiedKFold from fastFM import sgd import os import xgboost as xgb def preprocessing001(): print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') members = pd.read_csv(data_path + 'members.csv') print('Data preprocessing...') song_cols = songs.columns #['song_id', 'artist_name', 'genre_ids', 'song_length', 'language'] train = train.merge(songs[song_cols], on='song_id', how='left') test = test.merge(songs[song_cols], on='song_id', how='left') members['registration_year'] = members['registration_init_time'].apply(lambda x: int(str(x)[0:4])) members['registration_month'] = members['registration_init_time'].apply(lambda x: int(str(x)[4:6])) members['registration_date'] = members['registration_init_time'].apply(lambda x: int(str(x)[6:8])) members['expiration_year'] = members['expiration_date'].apply(lambda x: int(str(x)[0:4])) members['expiration_month'] = members['expiration_date'].apply(lambda x: int(str(x)[4:6])) members['expiration_date'] = members['expiration_date'].apply(lambda x: int(str(x)[6:8])) members = members.drop(['registration_init_time'], axis=1) members_cols = members.columns train = train.merge(members[members_cols], on='msno', how='left') test = test.merge(members[members_cols], on='msno', how='left') train = train.fillna(-1) test = test.fillna(-1) import gc del members, songs; gc.collect(); cols = list(train.columns) cols.remove('target') for col in tqdm(cols): if train[col].dtype == 'object': train[col] = train[col].apply(str) test[col] = test[col].apply(str) le = LabelEncoder() train_vals = list(train[col].unique()) test_vals = list(test[col].unique()) le.fit(train_vals + test_vals) train[col] = le.transform(train[col]) test[col] = le.transform(test[col]) X = np.array(train.drop(['target'], axis=1)) y = train['target'].values X_test = np.array(test.drop(['id'], axis=1)) ids = test['id'].values return X,y,X_test def preprocessing_text(): print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') members = pd.read_csv(data_path + 'members.csv') songsinfo = pd.read_csv(data_path + "song_extra_info.csv") print('Data preprocessing...') df_train_merged = train.merge(songs[['song_id', 'genre_ids', 'artist_name', 'composer', 'lyricist']], on='song_id', how='left') df_test_merged = test.merge(songs[['song_id', 'genre_ids', 'artist_name', 'composer', 'lyricist']], on='song_id', how='left') df_train_merged[['genre_ids', 'artist_name', 'composer', 'lyricist']].fillna('', inplace=True) df_test_merged[['genre_ids', 'artist_name', 'composer', 'lyricist']].fillna('', inplace=True) df_train_merged['genre_ids'] = df_train_merged['genre_ids'].astype(str) df_test_merged['genre_ids'] = df_test_merged['genre_ids'].astype(str) df_train_merged['artist_name'] = df_train_merged['artist_name'].astype(str) df_test_merged['artist_name'] = df_test_merged['artist_name'].astype(str) df_train_merged['composer'] = df_train_merged['composer'].astype(str) df_test_merged['composer'] = df_test_merged['composer'].astype(str) df_train_merged['lyricist'] = df_train_merged['lyricist'].astype(str) df_test_merged['lyricist'] = df_test_merged['lyricist'].astype(str) df_train_merged['genre_ids_len'] = df_train_merged.genre_ids.str.split(r'|').apply(lambda x: len(x)) df_test_merged['genre_ids_len'] = df_test_merged.genre_ids.str.split(r'|').apply(lambda x: len(x)) df_train_merged['artist_name_len'] = df_train_merged.artist_name.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) df_test_merged['artist_name_len'] = df_test_merged.artist_name.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) df_train_merged['composer_len'] = df_train_merged.composer.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) df_test_merged['composer_len'] = df_test_merged.composer.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) df_train_merged['lyricist_len'] = df_train_merged.lyricist.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) df_test_merged['lyricist_len'] = df_test_merged.lyricist.str.split(r'[;|/\\,+、&]+').apply(lambda x: len(x)) def findfeat(merged): feat = merged['artist_name'].str.find('feat.') feat[feat == -1] = 0 feat[feat > 0] = 1 feat2 = merged['artist_name'].str.find('featuring') feat2[feat2 == -1] = 0 feat2[feat2 > 0] = 1 feat3 = feat + feat2 feat3[feat3 > 0] = 1 return feat3 df_train_merged['is_featured'] = findfeat(df_train_merged) df_test_merged['is_featured'] = findfeat(df_test_merged) df_train_merged['artist_composer'] = (df_train_merged['artist_name'] == df_train_merged['composer']).astype(np.int8) df_test_merged['artist_composer'] = (df_test_merged['artist_name'] == df_test_merged['composer']).astype(np.int8) df_train_merged['artist_composer_lyricist'] = ((df_train_merged['artist_name'] == df_train_merged['composer']) & ( df_train_merged['artist_name'] == df_train_merged['lyricist']) & ( df_train_merged['composer'] == df_train_merged[ 'lyricist'])).astype( np.int8) df_test_merged['artist_composer_lyricist'] = ((df_test_merged['artist_name'] == df_test_merged['composer']) & ( df_test_merged['artist_name'] == df_test_merged['lyricist']) & ( df_test_merged['composer'] == df_test_merged['lyricist'])).astype( np.int8) data = pd.concat((df_train_merged, df_test_merged)) songcount = data.groupby('song_id')[['msno']].count() songcount.reset_index(inplace=True) songcount.rename(columns={'msno': 'msno_count'}, inplace=True) usercount = data.groupby('msno')[['song_id']].count() usercount.reset_index(inplace=True) usercount.rename(columns={'song_id': 'song_count'}, inplace=True) print songcount.dtypes print usercount.dtypes df_train_merged = df_train_merged.merge(songcount, on='song_id', how='left') df_test_merged = df_test_merged.merge(songcount, on='song_id', how='left') df_train_merged = df_train_merged.merge(usercount, on='msno', how='left') df_test_merged = df_test_merged.merge(usercount, on='msno', how='left') print df_train_merged.dtypes # he values People local and People global are new in test set. replace by NAN df_test_merged['source_screen_name'] = df_test_merged['source_screen_name'].replace( ['People local', 'People global'], np.nan) newfeatcol = ['genre_ids_len', 'artist_name_len', 'composer_len', 'lyricist_len', 'is_featured', 'artist_composer', 'artist_composer_lyricist', 'msno_count', 'song_count'] return df_train_merged[newfeatcol], df_test_merged[newfeatcol] def preprocessing_source_type_source_screen_name_source_type(): print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') data = pd.concat((train[['msno', 'song_id','source_type','source_screen_name','source_system_tab']], test[['msno', 'song_id','source_type','source_screen_name','source_system_tab']])) print 'example size before drop duplicates' print len(data) data.drop_duplicates(subset=['msno', 'song_id'], keep="first", inplace=True) print 'example size after drop duplicates' print len(data) newfeat = None groups = data.groupby('msno') #print data #print groups['source_type'].count() for feature in ['source_type','source_screen_name','source_system_tab']: valuecount = groups[feature].value_counts(normalize=True,dropna=False) print valuecount valuecount = valuecount.unstack(level=-1).add_prefix(feature) # countsum = valuecount.sum(axis=0) # for col in valuecount.columns: # valuecount[col] *= 1.0 # valuecount[col] /= countsum if newfeat is None: newfeat = valuecount else: newfeat=newfeat.join(valuecount,how='left') newfeat.reset_index(inplace=True) train = train[['msno']].merge(newfeat,on='msno',how='left') test = test[['msno']].merge(newfeat, on='msno', how='left') return train,test def computeSVD(urm, K): U, s, Vt = sparsesvd(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) # U = csr_matrix(np.transpose(U), dtype=np.float32) # S = csr_matrix(S, dtype=np.float32) # Vt = csr_matrix(Vt, dtype=np.float32) return np.transpose(U), S.dot(Vt) def preprocessingwordembedding(latent=10): print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') members = pd.read_csv(data_path + 'members.csv') songsinfo = pd.read_csv(data_path + "song_extra_info.csv") print('Data preprocessing...') data = pd.concat((train[['msno', 'song_id']], test[['msno', 'song_id']])) data = data.merge(songs, on='song_id', how='left') data = data.merge(members, on='msno', how='left') data = data.merge(song_extra_info, on='song_id', how='left') def lgbm2(X_train, X_valid, y_train, y_valid, X_test, X_test_ids, params={'learning_rate': 0.4, "application": 'binary', "max_depth": 15, 'num_leaves': 2 ** 8, 'verbosity': 0, 'metric': 'auc', 'num_threads': 60}, num_boost_round=9000, early_stopping_rounds=10, categorical_feature=None,learning_rates=None,w=None,along=None,type=0): # p_test = bst.predict(X_test) import math weight = np.array(range(len(X_train))) if along is not None: day = pd.DataFrame(along) day.columns = ['timestamp'] dayunique = day['timestamp'].unique() dayunique.sort() mark = pd.DataFrame(dayunique) mark.columns = ['timestamp'] mark['rank'] = range(len(mark)) day = day.merge(mark, on='timestamp') weight = day['rank'].values if w is not None: if type == 0: weight = w*np.log((weight+1))+1 elif type == 1: weight = -w * np.log((-weight + 1)+len(X_train)) + w*math.log(len(X_train)+1)+1 else: weight = [1] * len(X_train) print w print len(weight) print len(X_train) d_train = lgb.Dataset(X_train,weight=weight, label=y_train) d_valid = lgb.Dataset(X_valid, label=y_valid) watchlist = [d_train, d_valid] print('Training LGBM model...') model = lgb.train(params, train_set=d_train, num_boost_round=num_boost_round, valid_sets=watchlist, early_stopping_rounds=early_stopping_rounds, verbose_eval=10,learning_rates=learning_rates) # if categorical_feature is not None: # model = lgb.train(params, train_set=d_train, num_boost_round=num_boost_round, valid_sets=watchlist, # early_stopping_rounds=early_stopping_rounds, verbose_eval=10,categorical_feature = categorical_feature) print('Making predictions and saving them...') p_valid = model.predict(X_valid) p_test = model.predict(X_test) subm = pd.DataFrame() subm['id'] = X_test_ids subm['target'] = p_test # subm.to_csv('submission.csv.gz', compression='gzip', index=False, float_format='%.6f') print('Done!') print "split feature importance" print model.feature_importance(importance_type='split') print "gain feature importance" print model.feature_importance(importance_type='gain') return subm , pd.DataFrame(p_valid),model <file_sep> from tqdm import tqdm from sklearn.preprocessing import LabelEncoder from scipy.sparse import csr_matrix from sparsesvd import sparsesvd import joblib import numpy as np import math import pandas as pd data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') songs = pd.read_csv(data_path + 'songs.csv') members = pd.read_csv(data_path + 'members.csv') data = pd.concat((train[['msno','song_id','target']],test[['msno','song_id']])) data = data.drop_duplicates() songs = pd.read_csv(data_path + 'songs.csv') for col in ['artist_name' ]:#,'composer','lyricist','genre_ids']: songs[col] = songs[col].str.replace(r'\([\s\S]+?\)','') songs[col] = songs[col].str.replace(r'([\s\S]+?)','') songs[col].fillna('',inplace=True) data = data.merge(songs,on='song_id',how='left') data['artist_name'].fillna('',inplace=True) user_groups = data.groupby('msno') msnoindex = user_groups['artist_name'].count().reset_index(drop=False) msnoindex['msno_id'] = range(len(msnoindex)) data = data.merge(msnoindex[['msno','msno_id']],on='msno',how='left') newfeat = [] matrixlist = [] lelist = [] #for col in ['artist_name']:#,'composer','lyricist','genre_ids']: col = 'artist_name' feat = user_groups[col].agg(lambda x: "|".join(x)) userfeat = feat.str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |') index=[] value=[] farray=userfeat for i in tqdm(range(len(farray))): vals = farray[i] if type(vals) is not list: pass else: for val in vals: value.append(val.strip()) index.append(i) le = LabelEncoder() le.fit(value) label = le.transform(value) matrix = csr_matrix(([1]*len(label),(index,label)),shape=(len(farray),max(label)+1)) matrixlist.append(matrix) lelist.append(le) def computeSVD(urm, K): U, s, Vt = sparsesvd(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = math.sqrt(s[i]) return np.transpose(U), S.dot(Vt) index=[] value=[] farray=data[col].str.split(r',|\||\\|&|\+|;|、| ,|and|/|feat.|features|featuring|with| X |').values for i in tqdm(range(len(farray))): vals = farray[i] if type(vals) is not list: pass else: for val in vals: value.append(val.strip()) index.append(i) itemfeat = le.transform(value) lastone = index[0] featstack = [] inter= [] for i in tqdm(xrange(len(itemfeat))): if index[i] == lastone: inter.append(itemfeat[i]) if i == len(index)-1: featstack.append(inter) else: featstack.append(inter) inter = [] inter.append(itemfeat[i]) lastone = index[i] msno_id = data['msno_id'].values svdsimi = None for latentspace in [180]: U, V = computeSVD(matrix.tocsc(), latentspace) similist = [] simimax = [] for i in tqdm(xrange(len(featstack))): simi_iter = [] simi_max = 0 for val in featstack[i]: simi = U[msno_id[i]].dot(V[:,val]) simi_iter.append(simi) if simi>simi_max: simi_max = simi # if simi<simi_min: # simi_min = simi # simi_mean += simi # if len(featstack[i]) >0: # simi_mean /=len(featstack[i]) # similist.append(simi_iter) simimax.append(simi_max) svdsimi = pd.Series(simimax) print pd.Series(simimax[:len(train)]).corr(train['target']) pd.DataFrame(svdsimi).to_csv("../out/simi/artist_name_svddot.csv",index=None,header=None) <file_sep># coding=utf-8 import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import lightgbm as lgb from tqdm import tqdm import xgboost as xgb from tempfile import mkdtemp from joblib import Memory from scipy.sparse import csc_matrix, csr_matrix, lil_matrix import math as mt import csv from sparsesvd import sparsesvd import joblib import os import langid from sklearn.metrics.pairwise import pairwise_distances from sklearn.model_selection import StratifiedKFold from fastFM import sgd from multiprocessing import Pool import sys from sklearn.metrics import pairwise_distances njobs = int(sys.argv[1]) print('Loading data...') data_path = "../data/" train = pd.read_csv(data_path + 'train.csv') test = pd.read_csv(data_path + 'test.csv') print('Data preprocessing merge and fillna and numeric encoding...') data = pd.concat((train[['msno', 'song_id', 'target']], test[['msno', 'song_id']])) le = LabelEncoder() data['msno_le'] = msnole = le.fit_transform(data['msno']) data['song_id_le'] = songle = le.fit_transform(data['song_id']) data_nodup = data.drop_duplicates(['msno_le','song_id_le']) uimatrix = csr_matrix(([1]*len(data_nodup),(data_nodup['msno_le'].values,data_nodup['song_id_le'].values))) print "construct similarity matrix" uicossimi = pairwise_distances(uimatrix,metric='cosine',n_jobs=60) uicossimi = 1-uicossimi uicossimi -= np.eye(uicossimi.shape[0]) uicossimi[uicossimi<1e-10]=0 print "sort simi" argsortindex = np.argsort(uicossimi) # iumatrix = uimatrix.transpose() iumatrix = iumatrix.tolil() for topn in [100]: index = [] for i in range(uicossimi.shape[0]): index.extend([i]*topn) maskmatrix = csr_matrix(([1]*topn*uicossimi.shape[0],(index,argsortindex[:,-topn:].flatten()))) uicossimiloc =(maskmatrix).multiply(uicossimi).tolil() def cfscore(input): uu_similoc = uicossimiloc[input[0]].tocsr().tocoo() iu_act = iumatrix[input[1]].tocsr().tocoo() return np.array(uu_similoc.multiply(iu_act).sum(axis=1)/topn).flatten() p = Pool(njobs) para = [] for i in range(max(njobs-1,10)): para.append((data['msno_le'].values[len(data)/njobs*(i):len(data)/njobs*(i+1)] ,data['song_id_le'].values[len(data)/njobs*(i):len(data)/njobs*(i+1)])) para.append((data['msno_le'].values[len(data)/njobs*(njobs-1):] ,data['song_id_le'].values[len(data)/njobs*(njobs-1):])) simi = p.map(cfscore, para) simiflatten = [] for val in simi: simiflatten.extend(val) #joblib.dump(simiflatten,filename="../out/simi/cf_cos_top%d.dump" % topn) simi_pd = pd.DataFrame(simiflatten) simi_pd.to_csv("../out/simi/cf_cos_top%d.csv" % topn,index=None,header=None)
53d6adf650adf21df6209b8c29678607cecedf29
[ "Markdown", "Python" ]
9
Markdown
xggman/WSDN_18_KKBOX_music_recommend
f563a25402cc048aba263f1c42739f7f9d708015
5b78f2d8ff0a26ab230483e592a35f560560470a
refs/heads/master
<repo_name>xuxiao415/Learning_Notes_of_Ethereum<file_sep>/Contracts/FAQs.md ## 2017-05-25 1. js包管理工具有哪些,都有什么区别? 比较流行的npm,bower,component. 现在比较常用的是npm,npm是随同NodeJS一起安装的包管理工具,能解决NodeJS代码部署上的很多问题,现在npm统一前后端只是时间问题。bower和component一般用于前端的模块化管理.[前端模块管理工具](http://www.ruanyifeng.com/blog/2014/09/package-management.html) 2. webpack webpack是近期最火的一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX)、coffee、样式(含less/sass)、图片等都作为模块来使用和处理。我们可以直接使用 require(XXX) 的形式来引入各模块,即使它们可能需要经过编译(比如JSX和sass),但我们无须在上面花费太多心思,因为 webpack 有着各种健全的加载器(loader)在默默处理这些事情. 3. 在一些开源框架中,dist文件夹是什么意思 全称是distribution。 在某些框架中,因为开发和发布是的内容或者代码形式是不一样的(比如利用Grunt压缩等等),这时候就需要一个存放最终发布版本的代码,这就是dist文件夹的用处 4. npm 安装参数中的 --save-dev 是什么意思 当你为你的模块安装一个依赖模块时,正常情况下你得先安装他们(在模块根目录下npm install module-name),然后连同版本号手动将他们添加到模块配置文件package.json中的依赖里(dependencies)。 -save和save-dev可以省掉你手动修改package.json文件的步骤。 spm install module-name -save 自动把模块和版本号添加到dependencies部分 spm install module-name -save-dve 自动把模块和版本号添加到devdependencies部分 至于配置文件区分这俩部分, 是用于区别开发依赖模块和产品依赖模块.它们真正的区别是,npm自己的文档说dependencies是运行时依赖,devDependencies是开发时的依赖。即devDependencies 下列出的模块,是我们开发时用的,比如 我们安装 js的压缩包gulp-uglify 时,我们采用的是 “npm install –save-dev gulp-uglify ”命令安装,因为我们在发布后用不到它,而只是在我们开发才用到它。dependencies 下的模块,则是我们发布后还需要依赖的模块,譬如像jQuery库或者Angular框架类似的,我们在开发完后后肯定还要依赖它们,否则就运行不了。 另外需要补充的是: 正常使用npm install时,会下载dependencies和devDependencies中的模块,当使用npm install –production或者注明NODE_ENV变量值为production时,只会下载dependencies中的模块。 5. [webpack解惑:require的五种用法](https://www.cnblogs.com/laneyfu/p/6158715.html) ## 2017-05-25 ## 2017-05-26 6. Invalid JASON RPC ## 2017-05-31 7. Everything in CryptoJS is big-endian. 8. [jquery中的event与originalEvent](http://www.jianshu.com/p/0c211d3ca896) 9. Uncaught RangeError: Maximum call stack size exceeded 可能是忘记调用event.stopPropagation(),它可以阻止事件的继续传播,在某些情况下可防止无限递归而导致浏览器崩溃 ## 2017-06-01 10. 如何获取non-constant function的返回值? 目前还不支持获取non-constant function的返回值,想要获取返回值,可以通过event来解决[问题连接](https://ethereum.stackexchange.com/questions/3285/how-to-get-return-values-when-function-with-argument-is-called) 11. transaction receipt 是什么? [https://ethereum.stackexchange.com/questions/6531/structure-of-a-transaction-receipt](https://ethereum.stackexchange.com/questions/6531/structure-of-a-transaction-receipt) 交易收据,交易的凭证,和transaction本身不同,数据结构不同。 transaction receipt 示例: ``` Result: { "blockHash": "0xe6b110c9167d9aabeb13b02a7b9358d879426474a79170403d67da33a391dbdc", "blockNumber": 665, "contractAddress": null, "cumulativeGasUsed": 68527, "from": "0x0fd8cd36bebcee2bcb35e24c925af5cf7ea9475d", "gasUsed": 68527, "logs": [ { "address": "0x91067b439e1be22196a5f64ee61e803670ba5be9", "blockHash": "0xe6b110c9167d9aabeb13b02a7b9358d879426474a79170403d67da33a391dbdc", "blockNumber": 665, "data": "0x00000000000000000000000000000000000000000000000000000000576eca940000000000000000000000000fd8cd36bebcee2bcb35e24c925af5cf7ea9475d0100000000000000000000000000000000000000000000000000000000000000", "logIndex": 0, "topics": [ "0x72d0d212148041614162a44c61fef731170dd7cccc35d1974690989386be0999" ], "transactionHash": "0xad62c939b2e865f13c61eebcb221d2c9737955e506b69fb624210d3fd4e0035b", "transactionIndex": 0 } ], "root": "7583254379574ee8eb2943c3ee41582a0041156215e2c7d82e363098c89fe21b", "to": "0x91067b439e1be22196a5f64ee61e803670ba5be9", "transactionHash": "0xad62c939b2e865f13c61eebcb221d2c9737955e506b69fb624210d3fd4e0035b", "transactionIndex": 0 } ``` Object - A transaction receipt object, or null when no receipt was found: [https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt](https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt) blockHash: String, 32 Bytes - hash of the block where this transaction was in. blockNumber: Number - block number where this transaction was in. transactionHash: String, 32 Bytes - hash of the transaction. transactionIndex: Number - integer of the transactions index position in the block. from: String, 20 Bytes - address of the sender. to: String, 20 Bytes - address of the receiver. null when its a contract creation transaction. cumulativeGasUsed: Number - The total amount of gas used when this transaction was executed in the block. gasUsed: Number - The amount of gas used by this specific transaction alone. contractAddress: String - 20 Bytes - The contract address created, if the transaction was a contract creation, otherwise null. logs: Array - Array of log objects, which this transaction generated. <file_sep>/在Docker中搭建以太坊私有链.md # 在Docker中搭建以太坊私有链 1. 制作Dockerfile,构建Ethereum镜像 Docker Hub上也有Ethereum-go镜像,这里打算自定义Ethereum-go镜像,官方镜像有两种,一种是基于Ubuntu的,另一种是基于Alpine Linux(一种轻量级的Linux发行版,包管理工具为apk,它的内置命令如下图)的,而这里也打算基于Alpine构建Ethereum-go镜像,因为Alpine镜像比较小,下载比较快.那为什么不用官方的呢,因为构建官方基于Alpine的Ethereum-go镜像的Dockerfile中有命令:`ENTRYPOINT [/geth]`,所以每次启动容器时还需要为其传入参数,想要进入shell界面,还需要在启动容器时使用参数`--entrypoint /bin/sh`(注意这里的参数是`docker run`的参数,而非geth(go实现的Ethereum客户端)的参数),比较麻烦,因而在自定义的Dockerfile中去掉了那条命令. ![Alpine Linux预置命令](./images/AlpineLinux.png) Dockerfile: ``` FROM alpine:3.5 RUN \ apk add --update go git make gcc musl-dev linux-headers ca-certificates && \ git clone --depth 1 https://github.com/ethereum/go-ethereum && \ (cd go-ethereum && make geth) && \ cp go-ethereum/build/bin/geth /geth && \ apk del go git make gcc musl-dev linux-headers && \ rm -rf /go-ethereum && rm -rf /var/cache/apk/* EXPOSE 8545 EXPOSE 30303 ``` 制作好Dockerfile后,在其所在的文件夹下运行`sudo docker build -t xuxiao415/privatechain:1.0 .`,这里`xuxiao415/privatechain`为镜像名称(`xuxiao415`为Docker Hub用户名,只有这样,`sudo docker push xuxiao415/privatechain:1.0`命令才能将构建的镜像推送上传到自己的Docker Hub上),`1.0`为标签或版本号. 这样就构建了基于Alpine的Ethereum-go镜像. 2. 搭建以太坊私有链 根据构建的镜像,启动多个容器,就可以得到多个以太坊节点,将这些节点连接起来就构成了一个以太坊私有链. * 启动容器 ``` sudo docker --name node1 -p 10001:30303 -p 10002:8545 -it xuxiao415/privatechain:1.0 /bin/sh ``` 这里还可以制定卷volume,使用参数`-v 主机文件夹绝对路径:容器文件夹绝对路径`.这里需要启动多个节点,这里启动两个节点.第二容器启动命令: ``` sudo docker --name node2 -p 10003:30303 -p 10004:8545 -it xuxiao415/privatechain:1.0 /bin/sh ``` * 启动geth客户端 在各个容器中启动依次如下命令: 第一个容器: ``` /geth --identity node1 --datadir /chaindata --networkid 7777 --nodiscover --rpccorsdomain "*" --rpc --rpcport "8545" --port "30303" --nat "any" --rpcapi "admin,eth,debug,miner,net,shh,txpool,personal,web3" console ``` 第二个容器: ``` /geth --identity node2 --datadir /chaindata --networkid 7777 --nodiscover --rpccorsdomain "*" --rpc --rpcport "8545" --port "30303" --nat "any" --rpcapi "admin,eth,debug,miner,net,shh,txpool,personal,web3" console ``` * 连接各节点 上个步骤中会进入geth控制台中,在控制台中连接两个节点.运行如下命令: ``` admin.addPeer('enode://id@ip:port') ``` id为对方geth的id,可在对方geth控制台中运行命令`admin.nodeInfo.id`得到;ip可在对方容器shell中运行`hostname -i`得到,或者在主机上运行`sudo docker inspect 容器名或容器id`得到;port默认为30303. 连接好后,可以运行命令`admin.peers`来查看连接的节点. 至此,以太坊私有链就搭建好了. ##注意: 选项datadir的文件夹与genesisBlock.json文件所在的文件夹尽量不要在一各文件夹下,不然容易出错 <file_sep>/startWorkspace.sh #!/bin/bash #启动分别装有Ethereum节点的两个容器和redis客户端redis-cli #<NAME> #2017-6-20 if tmux list-session -F "#{session_name}" | grep -q blockchain; then tmux kill-session -t blockchain fi tmux new-session -d -s blockchain tmux split-window -h tmux split-window -v tmux send-keys -t 0 "redis-cli -a 570978" C-m tmux send-keys -t 1 "sudo docker start node1_chain1" C-m tmux send-keys -t 1 "sudo docker attach node1_chain1" C-m tmux send-keys -t 2 "sudo docker start node2_chain1" C-m tmux send-keys -t 2 "sudo docker attach node2_chain1" C-m tmux attach -t blockchain <file_sep>/web3js学习笔记.md ### 2017-06-03 1. 如何确定Transaction的状态? [https://ethereum.stackexchange.com/questions/6002/transaction-status](https://ethereum.stackexchange.com/questions/6002/transaction-status) ### 2017-06-06 1. 如何解析transaction receipt的log? [https://ethereum.stackexchange.com/questions/1381/how-do-i-parse-the-transaction-receipt-log-with-web3-js](https://ethereum.stackexchange.com/questions/1381/how-do-i-parse-the-transaction-receipt-log-with-web3-js) <file_sep>/Contracts/plan.md # 以太坊学习计划 ### 2017-05-24 学习truffle框架和web3 API 额外学习:模块管理工具webpack ### 2017-05-25 学习bootstrap,深入学习web3 API <file_sep>/在Docker中搭建智能合约开发环境.md # 基于Docker搭建智能合约开发环境 --- ### 在Docker中搭建智能合约开发环境 基于Docker搭建以太坊私有链([搭建私有链链接](https://github.com/xuxiao415/Learning_Notes_of_Ethereum/blob/master/%E5%9C%A8Docker%E4%B8%AD%E6%90%AD%E5%BB%BA%E4%BB%A5%E5%A4%AA%E5%9D%8A%E7%A7%81%E6%9C%89%E9%93%BE.md)),并在每个节点上安装solc编译器.这样每个节点中就可以编译并部署智能合约了(切记,部署智能合约时一定不要忘了挖矿,不然智能合约无法部署到区块链上).这里所用的Ethereum客户端依然是geth.geth本身可以部署智能合约,但却不能编译,因而需要solc来编译智能合约. 在Docker中安装solc编译器.这里依然需要制作Dockerfile来构建Docker镜像. Dockerfile: ``` FROM xuxiao415/ethereum-go:alpine MAINTAINER xuxiao415 "<EMAIL>" RUN \ apk --no-cache --update add build-base cmake boost-dev git && \ sed -i -E -e 's/include <sys\/poll.h>/include <poll.h>/' /usr/include/boost/asio/detail/socket_types.hpp && \ git clone --depth 1 --recursive -b release https://github.com/ethereum/solidity && \ cd /solidity && cmake -DCMAKE_BUILD_TYPE=Release -DTESTS=0 -DSTATIC_LINKING=1 && \ cd /solidity && make solc && install -s solc/solc /usr/bin && \ cd / && rm -rf solidity && \ apk del sed build-base git make cmake gcc g++ musl-dev curl-dev boost-dev && \ rm -rf /var/cache/apk/* ``` 这里的`xuxiao415/ethereum-go`镜像的Dockerfile为: ``` FROM alpine:3.5 RUN \ apk add --update go git make gcc musl-dev linux-headers ca-certificates && \ git clone --depth 1 https://github.com/ethereum/go-ethereum && \ (cd go-ethereum && make geth) && \ cp go-ethereum/build/bin/geth /geth && \ apk del go git make gcc musl-dev linux-headers && \ rm -rf /go-ethereum && rm -rf /var/cache/apk/* EXPOSE 8545 EXPOSE 30303 ``` 构建镜像时尽量在科学上网的情况下,不然有可能会失败. 构建好镜像后,就可以启动容器,也即以太坊节点,并把各节点连接起来,之后就可以在容器的`shell`界面创建`.solc`或`.sol`文件,并使用solc编译了([solc编译器使用说明](https://github.com/ethereum/solidity/blob/develop/docs/using-the-compiler.rst),还可以在命令行使用`--help`查看solc的使用方法),之后就可以在geth控制台部署智能合约了.也可以不创建solc文件编写智能合约,直接在geth控制台中编写智能合约,就是比较麻烦,因为在控制台中智能合约代码不能换行缩进,不易编写智能合约,所以不建议使用,不过官方的第一个智能合约greeter确实在geth控制台中写的,不过现在在控制台中编译solc文件的方法已经在geth-1.6中被删除了,编译时会提示找不到方法. --- ### 在Docker外搭建智能合约开发环境 上一种方法中,智能合约的整个开发过程完全可以在Docker容器中完成,但就是在编写智能合约时,比较麻烦,因为在创建的Docker容器中似乎只有vi编辑器,对新人来说,不太适合,因而这里打算使用智能合约开发的IDE--Remix.Remix是一个Solidity语言的集成开发环境,也就是智能合约的开发环境,它可以集编译、部署智能合约于一身,非常方便.它是在线的IDE,也就是只要有浏览器不用安装就可以直接使用.之前的集成开发环境是Mix,但现在换成了Remix. 这里的Remix是在主机上运行的,因为Docker中没有图形界面,无法安装谷歌等浏览器,只能在主机上使用Remix,然后通过RPC连接Docker中的以太坊私有链节点. 1. 首先启动[Remix](http://remix.ethereum.org),这里注意不要使用https,谷歌默认使用https,所以在输入网址时,去掉s,否则将连接失败,如下图: ![Remix](./images/Remix.png) 2. 使Remix连接以太坊私有链节点,前提是私有链已经启动,并且启动时使用参数`--rpc --rpcaddr ip`,这里的`ip`是节点所在Docker容器的ip地址,不是`127.0.0.1`,也不是`localhost`,而是它的外网ip地址,在容器中的shell中使用命令`hostname -i`即可得到ip地址,或在主机中使用`sudo docker inpect name`,其中`name`为Docker容器的名字.还有一点就是,在创建容器时要将主机的某个端口与容器进行映射,使用参数`-p host_port:container_port`,一般`container_port`为`8545`,geth的RPC API就是使用的这个端口,这一点格外重要,因为主机上的Remix就是通过RPC API连接的以太坊私有链节点.以上准备工作做好以后就可使用Remix连接节点了,步骤如下: * 在Remix右上角点击Contract ![Contract](./images/Contract.png) * 找到Select execution environment选项,选择Web3 Provider ![execution_environment](./images/execution_environment.png) * 将端口号8545更改为与容器端口8545映射的主机端口`host_port`,点击OK即可连接你的私有链节点了 ![web3 Provider Endpoint](./images/web3ProviderEndpoint.png) 以上就是两种搭建智能合约开发环境的两种方法. <file_sep>/README.md # Learning_Notes_of_Ethereum # 以太坊学习笔记 包含以太坊中的一些名词解释和其他的内容介绍 <file_sep>/redis学习笔记.md 1. redis-cli 中输入 `config set requirepass password` 即可设置数据库密码 2. redis-cli 中输入 `config get dir` 即可获取数据库文件位置 3. 在终端输入 `redis-cli shutdown` 可关闭redis-cli 4. ubuntu下关闭、开启和重启redis-server的命令 ``` /etc/init.d/redis-server stop /etc/init.d/redis-server start /etc/init.d/redis-server restart ``` <file_sep>/linux学习笔记.md ### 用过的命令 1. locate locate命令用于查找文件,它比find命令的搜索速度快,它需要一个数据库,这个数据库由每天的例行工作(crontab)程序来建立。当我们建立好这个数据库后,就可以方便地来搜寻所需文件了。 即先运行:updatedb(无论在那个目录中均可,可以放在crontab中 )后在 /var/lib/slocate/ 下生成 slocate.db 数据库即可快速查找。在命令提示符下直接执行#updatedb 命令即可: 例如:查找相关字issue ``` $ locate issue /etc/issue /etc/issue.net /usr/man/man5/issue.5 /usr/man/man5/issue.net.5 ``` 2. netstat 用于显示各种网络相关信息 常用其查看端口占用情况 ``` $ netstat -apn ``` 显示所有端口,可与grep连用,过滤所要查询的端口占用 3. kill 杀死进程,强制杀死加`-9` 4. tmux 是一个非常好用的终端复用工具. [tmux比较好的配置文件](https://github.com/gpakosz/.tmux) [tmux脚本教程](http://codingjunkie.net/kafka-tmux/) 5. vim 格式化shell代码 * 按两下小写g,即gg,定位光标到第一行。 * 按住Shift+v,即大写V,进入可视化编辑的列编辑模式。 * Shift+g,即大写G,选中整个代码。 * 按下等号=,格式化所有代码。 6. vim选中字符复制/剪切/粘贴 使用normal模式下的 v命令,进入visual模式,v+ j/k/h/l 进行文本选中 对于选中的文本进行如下按键: d ------ 剪切操作 y -------复制操作 p -------粘贴操作 ^ --------选中当前行,光标位置到行首(或者使用键盘的HOME键) $ --------选中当前行,光标位置到行尾(或者使用键盘的END键) 7. Oh My ZSH! Oh-My-Zsh is an open source, community-driven framework for managing your ZSH configuration. 8. chsh 修改linux默认shell,使用方法:使用 `chsh -h` 查看 9. `cat /etc/shells` 查看linux可用的shell 10. `chmod a+x filename` 对于filename文件,所有用户均获得执行此文件的权限 <file_sep>/Solidity学习笔记.md ### 2017-06-01 1. Events events 可以让我们很方便地使用 EVM 记录(日志)工具,它可以用于调用 DAPP 用户界面的 JavaScript 回调函数,这些回调函数监听着这些事件(events). events 是智能合约中可以继承的成员. 当 events 被调用时,它们会将参数存储在 transaction 的 log 中,log 是区块链中一种特殊的数据结构. 这些 logs 和智能合约的地址相关,它们被整合进区块链中,只要存储它们的区块可以访问,它们会一直存在(Frontier 和 Homestead 是这样,Serenity可能会改变这一特性). log 和 event data 在智能合约中是不可以访问的,即便是创建它们的智能合约也不可以访问. 在 events 进行声明时,最多有三个参数的前缀可以加 indexed,加了 indexed 的参数就可以通过特定的值过滤搜索它们. 加了 indexed 的参数的值不会被存储,只能通过它们的值搜索它们. 2. signature of an event is a topic. And also very index argument is a topic. [https://ethereum.stackexchange.com/questions/12950/what-are-event-topics](https://ethereum.stackexchange.com/questions/12950/what-are-event-topics) ### 2017-06-02 1. cumulativeGasUsed is the sum of gasUsed by this transaction and all preceding transactions in the same block. [https://ethereum.stackexchange.com/questions/3346/what-is-and-how-to-calculate-cumulative-gas-used](https://ethereum.stackexchange.com/questions/3346/what-is-and-how-to-calculate-cumulative-gas-used) ### 2017-08-16 1. 函数返回多个值   一种方法是通过元组(tuple)实现,另一种方法是通过返回多个函数中的局部变量实现 2. fallback函数,function(){},它是个匿名函数,当用户向其所在的智能合约发送ether时,自动执行. 一般它需要配合payable modifier使用,使得该函数能接收ether,并对其做相应的处理,function()payable{} <file_sep>/以太坊学习笔记.md # 以太坊学习笔记 ## 以太坊的发展阶段 - Frontier(2015.7) 以太坊的第一个阶段 - Homestead(2016.3) 以太坊的第二个阶段,protocol changes,networking change。 EIP-2 主要的Homestead硬分叉改变 EIP-7 硬分叉相对应的EVM(以太坊虚拟机)更新:DELEGATECALL EIP-8 devp2p 向前兼容性 EIP是指以太坊改进提议(Ethereal Improvement Proposal - Metropolis(2016.3) - Serenity(2017.1) ## 以太坊账户 - Externally Owned Accounts (EOAs) 这类账户由私钥控制,其实也就是由人来控制的 - Contract Accounts 这类账户由合约代码控制,它是由EOA来激活的 ## 智能合约 ## 以太坊私有链 [以太坊私有链搭建](https://github.com/ethereum/go-ethereum/wiki/Setting-up-private-network-or-local-cluster) --- 1. 如果你要建立的私有链中的节点在一个局域网中,并且没有和公网连接,我们可以手动启动多个节点,通过在geth客户端中手动添加peers即可将各个节点连接起来,这样就构成了一个简单的私有链。但是这样的私有链并不安全,一旦连接公网,私有链有可能被破坏。 2. 如果想建立一个和公网隔离的私有链,可以在启动节点时,更改启动参数**networkid**(公网的networkid为1,Modern为2,它一个测试网络,不过已经被弃用,3是另一个新的测试网络),这样只有**networkid**和你相同的节点才能发现你,并连接到你的节点。 ## Alpine Linux一个轻量级Linux发行版,适合作为docker的基础镜像,大小仅为5M左右,Ethereum的docker镜像就是以它为基础构建的,它的包管理工具为apk,默认shell为ash ## Remix Solidity的集成开发环境,之前的开发环境是Mix,现已不再使用 ## Truffle Truffle is the most popular development framework for Ethereum with a mission to make your life a whole lot easier.
e57a5a14fc489b66fcc999d864edf2107d83c936
[ "Markdown", "Shell" ]
11
Markdown
xuxiao415/Learning_Notes_of_Ethereum
2dd028676f51ce26906b5bedfdb93b4881811aa7
ac3b250223d756e33a5acba8ad3a603ca1448866
refs/heads/master
<repo_name>fl00r/component<file_sep>/graph.go package component import ( "container/list" "errors" ) // Graph represented by string vertices and linked list of strings for edges type Graph struct { vertices map[string]map[string]bool } // NewGraph returns empty Graph type func NewGraph() *Graph { return &Graph{make(map[string]map[string]bool)} } // AddEdge connects two vertices by adding vertice2 to vetice1's list of edges func (g *Graph) AddEdge(verticeFrom, verticeTo string) *Graph { edgesFrom := g.vertices[verticeFrom] if edgesFrom == nil { g.vertices[verticeFrom] = make(map[string]bool) edgesFrom = g.vertices[verticeFrom] } edgesFrom[verticeTo] = true edgesTo := g.vertices[verticeTo] if edgesTo == nil { g.vertices[verticeTo] = make(map[string]bool) } return g } // TopologicalSort not-generic ^^ topological sort function for our Graph type // // Kahn's algorithm func (g Graph) TopologicalSort() ([]string, error) { verticesCount := len(g.vertices) sortedVertices := make([]string, 0, verticesCount) startingVertices := list.New() for k, v := range g.vertices { if len(v) == 0 { startingVertices.PushBack(k) } } if startingVertices.Len() == 0 { return nil, errors.New("Graph is not acycle") } for v := startingVertices.Front(); v != nil; v = v.Next() { val := v.Value.(string) delete(g.vertices, val) sortedVertices = append(sortedVertices, val) for k, w := range g.vertices { if w[val] { delete(w, val) if len(w) == 0 { startingVertices.PushBack(k) } } } } if len(g.vertices) != 0 { return nil, errors.New("Graph is not acycle") } return sortedVertices, nil } <file_sep>/README.md # Component Dependency Injection for golang. Inspired by [stuartsierra/component](https://github.com/stuartsierra/component). It is hardly be as elegant as in Clojure though. It is type unsafe and I don't know how it could be fixed with current golang state. # Usage ```go package main import github.com/fl00r/component // imaginable postgresql driver import pg type Database { host string port int database string connection *pg.connection } type Scheduler { threadPoolSize int } type App { logLevel string } func NewDatabase(args ...interface{}) component.Lifecicle { return &Database{ host: args[0].(string), port: args[1].(int), database: args[2].(string), } } func (d *Database) Start(dependencies ...interface{}) error { d.connection, err := pg.Connect(d.host, d.port, d.database) return err } func (d *Database) Stop() error { err := d.connection.Close() d.connection = nil return err } // ... // same for Scheduler and App types // func main() { system = component.New() system. NewComponent("database"). Constructor(NewDatabase). Args("localhost", 5432, "dev_database") system. NewComponent("scheduler"). Constructor(NewScheduler). Args(12). Dependencies("database") system. NewComponent("app"). Constructor(NewApp). Args("Error"). Dependencies("database", "scheduler") system.Start() defer system.Stop() } ``` <file_sep>/component_test.go package component import ( "fmt" "testing" ) type SomeComponent struct { number int } func NewSomeComponent(numbers ...interface{}) Lifecycle { c := SomeComponent{numbers[0].(int)} return &c } func (comp *SomeComponent) Start(components ...interface{}) error { for _, c := range components { comp.number += c.(*SomeComponent).number } fmt.Println(comp.number) return nil } func (comp *SomeComponent) Stop() error { comp.number = 0 return nil } func TestSystem(t *testing.T) { system := NewSystem() system. NewComponent("component-1"). Constructor(NewSomeComponent). Args(1) system. NewComponent("component-2"). Constructor(NewSomeComponent). Args(2). Dependencies("component-1") component3 := system. NewComponent("component-3"). Constructor(NewSomeComponent). Args(3). Dependencies("component-1", "component-2") err := system.Start() if err != nil { panic(err) } exp := 7 n := component3.entity.(*SomeComponent).number if exp != n { t.Errorf("%d != %d", exp, n) t.Fail() } err = system.Stop() if err != nil { panic(err) } exp = 0 n = component3.entity.(*SomeComponent).number if exp != n { t.Errorf("%d != %d", exp, n) t.Fail() } } <file_sep>/component.go package component // System ... type System struct { components map[string]*Component } // Component ... type Component struct { name string constructor func(args ...interface{}) Lifecycle args []interface{} dependencies []string entity Lifecycle } // Lifecycle ... type Lifecycle interface { Start(dependencies ...interface{}) error Stop() error } // NewSystem ... func NewSystem() *System { components := make(map[string]*Component) system := System{ components: components, } return &system } // NewComponent ... func (s *System) NewComponent(name string) *Component { comp := Component{ name: name, } s.components[name] = &comp return &comp } // Constructor ... func (c *Component) Constructor(f func(args ...interface{}) Lifecycle) *Component { c.constructor = f return c } // Args ... func (c *Component) Args(args ...interface{}) *Component { c.args = args return c } // Dependencies ... func (c *Component) Dependencies(args ...string) *Component { c.dependencies = args return c } // Start ... func (s *System) Start() error { graph := NewGraph() for dep, component := range s.components { for _, d := range component.dependencies { graph.AddEdge(dep, d) } } vertices, err := (*graph).TopologicalSort() if err != nil { return err } for _, vertice := range vertices { component := s.components[vertice] entity := component.constructor(component.args...) dependencies := make([]interface{}, len(component.dependencies)) for i, dep := range component.dependencies { dependencies[i] = s.components[dep].entity } entity.Start(dependencies...) component.entity = entity } return nil } // Stop ... func (s *System) Stop() error { for _, c := range s.components { err := c.entity.Stop() if err != nil { return err } } return nil }
145f2f83de4bd2003622e94b6c286d0c3fd40e69
[ "Markdown", "Go" ]
4
Go
fl00r/component
0c0b938fc7ca649365989f85463a2adc4581ae57
87bd6469aca7e0d373dac9e163a4e57cc93cee41
refs/heads/master
<file_sep>/*___________________________________________ SOURCE CODE ASSET OF SAMUEL ROBENS-PARADISE © 2018-2019 DISTRIBUTION OF CODE WITHOUT WRITTEN CONSENT OF SAMUEL ROBENS-PARADISE IS PROHIBITED UNLESS ACCESSED THROUGH PUBLIC DOIMAIN SUCH AS GITHUB OR ANY OTHER OPEN SOURCE PLATFORM ON WHICH ASSET WAS PUBLISHED WITH AUTHOR CONSENT ________________________________________________ */ import React, { Component } from 'react'; import { Container, Row, Col } from 'reactstrap'; import './App.css'; import './Profile.css'; import './assets/inkstainprofile.svg'; class Profile extends Component { constructor(props){ super(props); this.state = { videoLink: "https://player.vimeo.com/video/300380587", sectionTitle: 'Profile', sectionDefinition: 'The backstory to <NAME>', videoDescription: "Emily's reel" } } render() { //generating local css classes... var localCSSclasses = { inkstainBackground: 'inkstainbottom', sectionHeader: 'sectionheader', sectionSubHeader: 'sectionsubheader', vimeoVideoFormat: 'vimeovideoformat', vimeoVideoInternal: 'vimeovideo_outer', EmilyBandelBioPic: 'emilybandelbiopic' } //generating props from parent class... let {EmilyInfo} = this.props; //generating local html elements... let sectionName = <h1 className={localCSSclasses.sectionHeader}><span>{this.state.sectionTitle}</span></h1> let sectionMinheader = <h2 className={localCSSclasses.sectionSubHeader}><span>{this.state.sectionDefinition}</span></h2> let EmilyReel = <h2 className={localCSSclasses.sectionSubHeader}><span>{this.state.videoDescription}</span></h2> return ( <div className={localCSSclasses.inkstainBackground}> <Container> {sectionName} {sectionMinheader} {EmilyReel} </Container> <Container> <Row> <Col xs="0" sm="1"></Col> <Col xs="12" sm="10"> <Container> <div className={localCSSclasses.vimeoVideoInternal}><iframe title="<NAME>" src="https://player.vimeo.com/video/300380587" className={localCSSclasses.vimeoVideoFormat} frameBorder="0" webkitallowfullscreen="true" mozallowfullscreen="true" allowFullScreen={true}></iframe></div><script src="https://player.vimeo.com/api/player.js"></script> </Container> </Col> <Col xs="0" sm="1"></Col> </Row> <Row> <Col xs="12" sm="12"><div className={localCSSclasses.EmilyBandelBioPic}>{EmilyInfo.bioPic}</div></Col> </Row> </Container> </div> ); } } export default Profile; <file_sep>/*___________________________________________ SOURCE CODE ASSET OF SAMUEL ROBENS-PARADISE © 2018-2019 DISTRIBUTION OF CODE WITHOUT WRITTEN CONSENT OF SAMUEL ROBENS-PARADISE IS PROHIBITED UNLESS ACCESSED THROUGH PUBLIC DOIMAIN SUCH AS GITHUB OR ANY OTHER OPEN SOURCE PLATFORM ON WHICH ASSET WAS PUBLISHED WITH AUTHOR CONSENT ________________________________________________ */ import React, { Component } from 'react'; import './App.css'; import { Collapse, Navbar, NavbarToggler, Nav, NavItem, NavLink } from 'reactstrap'; class Navigation extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isOpen: false, profileFlag: true, ContactFlag: true, profileHook: "profile", contactHook: "contact" }; } toggle() { this.setState({ isOpen: !this.state.isOpen }); } _sendNavFlagProfile = () => { if (!this.state.profileFlag) { this.setState({ profileFlag: true }); } this.props.navigationFlagIntermediateProfile(this.state.profileFlag); this.props.navigationHookIntermediate(this.state.profileHook); }; get sendNavFlagProfile() { return this._sendNavFlagProfile; } set sendNavFlagProfile(value) { this._sendNavFlagProfile = value; } _sendNavFlagContact = () => { if (!this.state.ContactFlag) { this.setState({ ContactFlag: true }); } this.props.navigationFlagIntermediateContact(this.state.ContactFlag); this.props.navigationHookIntermediate(this.state.contactHook); }; get sendNavFlagContact() { return this._sendNavFlagContact; } set sendNavFlagContact(value) { this._sendNavFlagContact = value; } render() { return ( <div> <Navbar className='navigate' expand="xs"> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className="ml-auto" navbar> <NavItem> <NavLink><span id="profile-navigation" onClick={this.sendNavFlagProfile} className="Navigationcss">Profile</span></NavLink> </NavItem> <NavItem> <NavLink ><span id="contact-navigation" onClick={this.sendNavFlagContact} className="Navigationcss" >Contact</span></NavLink> </NavItem> </Nav> </Collapse> </Navbar> </div> ); } } export default Navigation; <file_sep>/*___________________________________________ SOURCE CODE ASSET OF SAMUEL ROBENS-PARADISE © 2018-2019 DISTRIBUTION OF CODE WITHOUT WRITTEN CONSENT OF SAMUEL ROBENS-PARADISE IS PROHIBITED UNLESS ACCESSED THROUGH PUBLIC DOIMAIN SUCH AS GITHUB OR ANY OTHER OPEN SOURCE PLATFORM ON WHICH ASSET WAS PUBLISHED WITH AUTHOR CONSENT ________________________________________________ */ import React, { Component } from 'react'; import { Container, Row, Col } from 'reactstrap'; import './App.css'; import './Filmography.css'; import './assets/inkstainfilm.svg'; import StandingRoomOnly from './img/standing_room_only.jpg'; import ATwistedFate from './img/TF_poster.jpg'; import DeathRomantisized from './img/DR_poster.jpg'; import Poignant from './img/P_poster.jpg'; import Wick from './img/Wick_poster.jpg'; // This class corresponds to the filmography section of the website. Data that is associated with this component // is stored locally to this class. class Filmography extends Component { constructor(props){ super(props); this.state = { sectionTitle: 'Filmography', sectionDefinition: 'A collection of works, films and screenings ft. <NAME>', images: { StangingRoomCover: StandingRoomOnly, TwistedFateCover: ATwistedFate, DeathRomantisizedCover: DeathRomantisized, PoignantCover: Poignant, WickCover: Wick }, movieDescriptions: { StandingRoomOnlyDescription: "The interactions among 6 people in line and an Usher outside a movie theater. A short film adaptation of <NAME>'s stage-play, Standing Room Only. Emily plays a gothic character who is the first to arrive in line and camps out in a lawn chair.", ATwistedFateDescription: "Two roommates find a book that contains answers to the past, present and future. Riley (played by Emily) is hesitant at first, but eventually she concedes and agrees to read the book in order to find out what happened to her dad. The two end up summoning a demon by mistake. Riley battles the demon in a game of chess both mentally and physically, to get her roommate back and get answers about her dad. ", DeathRomantisizedDescription: "Death is played by a women who entices a doctor into killing his patients, but when one patient named Nina (played by Emily), makes a connection with the doctor after he kills her brother, he has to choose between dark and light.", PoignantDescription: "Poignant follows a woman who purchases a building to open her own health care center, unaware of the Entity named Maggie that haunts the building (Played by Emily). Maggie was abused and murdered and needs redemption for what happened to her before she can rest in peace.", WickDescription: "Wick is a computer game made by Hellbent Games. Emily voices one of the kids who warns against entering the forest at night." } } } componentDidMount(){ setTimeout( () => { this.setState({ images: { StangingRoomCover: StandingRoomOnly, TwistedFateCover: ATwistedFate, DeathRomantisizedCover: DeathRomantisized, PoignantCover: Poignant, WickCover: Wick } }) },300) } render() { //generating local css classes object... var localCSSclasses = { inkstainBackground: 'inkstainmiddle', sectionHeader: 'sectionheader', sectionSubHeader: 'sectionsubheader', standingRoomOnly: 'standing_room_only_image', aTwistedFate: 'a_twisted_fate', DeathRomantisizedCSS: 'death_romantasized', PoignantCSS: 'Poingnant_CSS', WickCSS: 'wick_CSS', localCSSTransitionClasses: { contain: 'contain', overlay: 'overlay', textStyle: 'text' } } let sectionName = <h1 className={localCSSclasses.sectionHeader}><span>{this.state.sectionTitle}</span></h1> let sectionMinheader = <h2 className={localCSSclasses.sectionSubHeader}><span>{this.state.sectionDefinition}</span></h2> //generating feature components... let SRObanner = <img className={localCSSclasses.standingRoomOnly} src={this.state.images.StangingRoomCover} alt ='Standing Room Only'></img> let TFbanner = <img className={localCSSclasses.aTwistedFate} src={this.state.images.TwistedFateCover} alt="A Twisted Fate"></img> let DRbanner = <img className={localCSSclasses.DeathRomantisizedCSS} src={this.state.images.DeathRomantisizedCover} alt='Death Romantisized'></img> let Pbanner = <img className={localCSSclasses.PoignantCSS} src={this.state.images.PoignantCover} alt='Poignant'></img> let Wickbanner= <img className={localCSSclasses.WickCSS} src={this.state.images.WickCover} alt= "Wick"></img> return ( <div className={localCSSclasses.inkstainBackground}> <Container>{sectionName} {sectionMinheader} </Container> <Container> <Row> <Col xs="12" md="4"> <Container> <div className={localCSSclasses.localCSSTransitionClasses.contain}> {SRObanner} <div className={localCSSclasses.localCSSTransitionClasses.overlay+" "+localCSSclasses.localCSSTransitionClasses.textStyle}> {this.state.movieDescriptions.StandingRoomOnlyDescription} </div> </div> </Container> </Col> <Col xs="12" md="4"><Container> <div className={localCSSclasses.localCSSTransitionClasses.contain}> {TFbanner} <div className={localCSSclasses.localCSSTransitionClasses.overlay+" "+localCSSclasses.localCSSTransitionClasses.textStyle}> {this.state.movieDescriptions.ATwistedFateDescription} </div> </div> </Container></Col> <Col xs="12" md="4"><Container> <div className={localCSSclasses.localCSSTransitionClasses.contain}> {DRbanner} <div className={localCSSclasses.localCSSTransitionClasses.overlay+" "+localCSSclasses.localCSSTransitionClasses.textStyle}> {this.state.movieDescriptions.DeathRomantisizedDescription} </div> </div> </Container></Col> </Row> <Row> <Col xs="12" md="4"><Container> <div className={localCSSclasses.localCSSTransitionClasses.contain}> {Pbanner} <div className={localCSSclasses.localCSSTransitionClasses.overlay+" "+localCSSclasses.localCSSTransitionClasses.textStyle}> {this.state.movieDescriptions.PoignantDescription} </div> </div> </Container></Col> <Col xs="12" md="8"><Container> <div className={localCSSclasses.localCSSTransitionClasses.contain}> {Wickbanner} <div className={localCSSclasses.localCSSTransitionClasses.overlay+" "+localCSSclasses.localCSSTransitionClasses.textStyle}> {this.state.movieDescriptions.WickDescription} </div> </div> </Container></Col> </Row> </Container> </div> ); } } export default Filmography; <file_sep>/*___________________________________________ SOURCE CODE ASSET OF SAMUEL ROBENS-PARADISE © 2018-2019 DISTRIBUTION OF CODE WITHOUT WRITTEN CONSENT OF SAMUEL ROBENS-PARADISE IS PROHIBITED UNLESS ACCESSED THROUGH PUBLIC DOIMAIN SUCH AS GITHUB OR ANY OTHER OPEN SOURCE PLATFORM ON WHICH ASSET WAS PUBLISHED WITH AUTHOR CONSENT ________________________________________________ */ import React, { Component } from 'react'; import { Container, Row, Col } from 'reactstrap'; import './App.css'; import './Footer.css'; import instaLogo from './assets/instagram.svg'; import moviereel from './assets/moviereel.svg'; class Footer extends Component { constructor(props){ super(props); this.state = { privacyPolicy: "#", instagramLink: 'https://www.instagram.com/emilybandel/?hl=en', IMDBLink: 'https://www.imdb.com/name/nm6818003/', instagramLogo: instaLogo, IMDBLogo: moviereel } } render() { var localCSSclasses = { background: 'footerbackground', socialLinks: 'sociallink' } return ( <div className={localCSSclasses.background}> <Container> <Row> <Col xs="6" sm="6"><a href={this.state.instagramLink} target='blank_'><img className={localCSSclasses.socialLinks} src={this.state.instagramLogo} alt="instagram"></img></a></Col> <Col xs="6" sm="6"><a href={this.state.IMDBLink} target='blank_'><img className={localCSSclasses.socialLinks} src={this.state.IMDBLogo} alt='IMDB'></img></a></Col> </Row> </Container> </div> ); } } export default Footer;
f9a287631d9ec7ba3605c4091b0138151df3e27e
[ "JavaScript" ]
4
JavaScript
EmilyBandel/webpage-application
b9e4c245a22a80455d519e2a10b080827f532bf4
b61d59a05092f2f25ee0512a1bc4b9cbe2cca0db
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Collections; namespace CORUS_TestTask.Entity { public static class ReflectionUtils { public static string ToString(object entity) { StringBuilder sb = new StringBuilder(); var type = entity.GetType(); sb.AppendLine($"{type.Name} :"); foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string)) sb.Append($"{prop.Name} = {prop.GetValue(entity, null)} "); else if(prop.PropertyType.IsGenericType) { var list = prop.GetValue(entity) as IList; if (list == null) continue; var nested = prop.PropertyType.GetGenericArguments()[0]; sb.AppendLine($"With list of {nested.Name}"); foreach(var item in list) { sb.AppendLine(ToString(item)); } } } sb.AppendLine(new string('-',100)); return sb.ToString(); } } } <file_sep>using CORUS_TestTask.Entity; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace CORUS_TestTask { class Program { static string s_fileName = $@"C:\CorusTest\File_{new DateTime(2017,11,15,14,20,00).ToString("yyyy.MM.dd_HH.mm.ss")}.xml"; static void Main(string[] args) { var collection = GetCollection(); //Call task 1 WriteToFile(collection); var collectionFromFile = GetFromFile(); PrintCollection(collectionFromFile); //Call task 2 PrintGrouped(); //Call task3 PrintMaxDate(); Console.ReadLine(); } //Part1 #region File private static void WriteToFile(IEnumerable<Pallet> collection) { try { using (FileStream fs = new FileStream(s_fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Pallet>)); xmlFormat.Serialize(fs, collection); } } catch(Exception ex) { Console.WriteLine(ex.Message); } } private static IEnumerable<Pallet> GetFromFile() { try { using (FileStream fs = new FileStream(s_fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { XmlSerializer xmlFormat = new XmlSerializer(typeof(List<Pallet>)); var result = xmlFormat.Deserialize(fs); return result as List<Pallet>; } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } #endregion private static void PrintCollection(IEnumerable<Pallet> collection) { foreach(var pal in collection) { Console.WriteLine(ReflectionUtils.ToString(pal)); } } //Part2 private static void PrintGrouped() { var collection = GetCollection(); var result = collection.GroupBy(p => p.EndDate).Select(p => new Pallet() { Boxes = collection. Where(c => c.EndDate == p.Key.Value). SelectMany(b => b.Boxes).OrderBy(b => b.Weight).ToList() }); foreach (var item in result) { Console.WriteLine($"Pallet with end date: {item.EndDate} and boxes:"); foreach (var box in item.Boxes) { Console.WriteLine(ReflectionUtils.ToString(box)); } } } //Part3 private static void PrintMaxDate() { var collection = GetCollection(); var result = collection.OrderByDescending(n => n.EndDate).Take(3).Select(p => new Pallet() { Boxes = p.Boxes.OrderBy(b => b.Dimension).ToList() }); foreach (var item in result) { Console.WriteLine($"Pallet with end date: {item.EndDate} and boxes:"); foreach (var box in item.Boxes) { Console.WriteLine(ReflectionUtils.ToString(box)); } } } private static IEnumerable<Pallet> GetCollection() { Random rnd = new Random(); return new List<Pallet>() { new Pallet() { Id = 1, Height =30, Width = 20, Depth = 55, Weight = 700, Boxes = new List<Box> { new Box() { Id = 11, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-20) }, new Box() { Id = 12, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-40) }, new Box() { Id = 13, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-70) } } }, new Pallet() { Id = 2, Height = 24.5f, Width = 22.3f, Depth = 43.8f, Weight = 671.3f, Boxes = new List<Box>() { new Box() { Id = 21, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-20) }, new Box() { Id = 22, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-50) }, new Box() { Id = 23, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-70) } } }, new Pallet() { Id = 3, Height =13.5f, Width = 22.4f, Depth = 11, Weight = 315.4f, Boxes = new List<Box>() { new Box() { Id = 31, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-10) }, new Box() { Id =32, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-3) }, new Box() { Id = 33, Height = rnd.NextDouble(), Width = rnd.NextDouble(), Depth = rnd.NextDouble(), Weight = rnd.NextDouble(), ProductionDate = new DateTime(2017,11,15,14,20,00).AddDays(-70) } } } }; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CORUS_TestTask.Entity { public abstract class EntityBase { public long Id { get; set; } public double Width { get; set; } public double Height { get; set; } public double Depth { get; set; } public virtual double Weight { get; set; } public virtual double Dimension => this.Weight * this.Height * this.Depth; } public sealed class Pallet : EntityBase { public List<Box> Boxes { get; set; } public Pallet() { Boxes = new List<Box>(); } public DateTime? EndDate => Boxes.Any() ? Boxes.Min(b=>b.EndDate): null; public override double Weight => Boxes.Sum(b => b.Weight) + 30; public override double Dimension => Boxes.Sum(b => b.Dimension) + base.Dimension; } public sealed class Box : EntityBase { //Term id days public int Term => 100; public DateTime? ProductionDate { get; set; } public DateTime? EndDate => this.ProductionDate.HasValue ? (DateTime?)this.ProductionDate.Value.AddDays(100) : null; } }
2beb03bc29221557a689f8aaa2eb32bbb0fcf3b0
[ "C#" ]
3
C#
Misha3739/CorusTestTask
370066c600f4da3f7094ef6bf7d5a87cec2fd07a
32be74ead40ca90d0ddb246ecda4fe435da56aca
refs/heads/master
<repo_name>mfkiwl/mxp-dataflow<file_sep>/README.md # mxp-dataflow MXP-DATAFLOW <file_sep>/work/poly/profile.sh ./poly_arm ./poly_neon ./poly_mxp <file_sep>/work/poly/run.sh make clean make source profile.sh
106632b6b47d4d4c851bbef3dcfb3c4f2f2b4097
[ "Markdown", "Shell" ]
3
Markdown
mfkiwl/mxp-dataflow
6c8b80bdb5439e849f1b44393ba4340441851bb7
fe5624ff241e9c3e77cbedb3c8f4440659c96254
refs/heads/master
<file_sep>extern crate aurelius; extern crate hyper; extern crate url; use aurelius::Server; use hyper::Client; use hyper::status::StatusCode; use url::Url; #[test] fn change_working_directory() { let mut server = Server::new(); server.start(); // Try to find a resource outside of the working directory. let http_port = server.http_addr().unwrap().port(); let mut resource_url = Url::parse(&format!("http://localhost:{}", http_port)).unwrap(); resource_url.set_path("/file"); let response = Client::new().get(resource_url.clone()).send().unwrap(); assert_eq!(response.status, StatusCode::NotFound); // Change to a directory where the file exists server.change_working_directory("tests/assets"); let response = Client::new().get(resource_url).send().unwrap(); assert_eq!(response.status, StatusCode::Ok); } <file_sep>//! Functions for interacting with browser processes. use std::process::{Command, Child, Stdio}; use std::io::Result; use url::Url; /// Opens a browser window at the specified URL in a new process. /// /// Returns an `io::Result` containing the child process. /// /// This function uses platform-specific utilities to determine the user's default browser. The /// following platforms are supported: /// /// | Platform | Program | /// | -------- | ---------- | /// | Linux | `xdg-open` | /// | OS X | `open -g | /// | Windows | `start` | /// /// # Panics /// Panics if called on an unsupported operating system. pub fn open(url: &str) -> Result<Child> { let (browser, args) = if cfg!(target_os = "linux") { ("xdg-open", vec![]) } else if cfg!(target_os = "macos") { ("open", vec!["-g"]) } else if cfg!(target_os = "windows") { // `start` requires an empty string as its first parameter. ("start", vec![""]) } else { panic!("unsupported OS") }; open_specific(url, &browser, &args) } /// Opens a specified browser in a new process. /// /// The browser will be called with any supplied arguments in addition to the URL as an additional /// argument. /// /// Returns an `io::Result` containing the child process. pub fn open_specific(url: &str, browser: &str, browser_args: &[&str]) -> Result<Child> { let url = Url::parse(url).unwrap(); debug!("starting process '{:?}' with url {:?}", browser, url); Command::new(browser) .args(browser_args) .arg(url.to_string()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() } <file_sep>//! Contains the WebSocket server component. use std::io; use std::net::{SocketAddr, TcpListener, TcpStream, ToSocketAddrs}; use std::sync::mpsc::channel; use std::thread; use chan; use websockets::{Message, Sender, Receiver, WebSocketStream}; use websockets::header::WebSocketProtocol; use websockets::message::Type; use websockets::server::Request; use websockets::result::WebSocketError; /// The WebSocket server. /// /// Manages WebSocket connections from clients of the HTTP server. pub struct Server { server: TcpListener, } impl Server { /// Creates a new server that listens on port `port`. pub fn new<A>(socket_addr: A) -> Server where A: ToSocketAddrs { Server { server: TcpListener::bind(socket_addr).unwrap() } } pub fn local_addr(&self) -> io::Result<SocketAddr> { self.server.local_addr() } fn handle_connection(connection: TcpStream, markdown_receiver: chan::Receiver<String>) { let stream = WebSocketStream::Tcp(connection); let request = Request::read(stream.try_clone().unwrap(), stream.try_clone().unwrap()) .unwrap(); let headers = request.headers.clone(); request.validate().unwrap(); let mut response = request.accept(); if let Some(&WebSocketProtocol(ref protocols)) = headers.get() { if protocols.contains(&("rust-websocket".to_string())) { response.headers.set(WebSocketProtocol(vec!["rust-websocket".to_string()])); } } let client = response.send().unwrap(); // Create the send and recieve channdels for the websocket. let (mut sender, mut receiver) = client.split(); // Create senders that will send websocket messages between threads. let (message_tx, message_rx) = channel(); // Message receiver let ws_message_tx = message_tx.clone(); let _ = thread::Builder::new() .name("ws_receive_loop".to_owned()) .spawn(move || { for message in receiver.incoming_messages() { let message: Message = match message { Ok(m) => m, Err(_) => { let _ = ws_message_tx.send(Message::close()); return; } }; match message.opcode { Type::Close => { let message = Message::close(); ws_message_tx.send(message).unwrap(); return; } Type::Ping => { let message = Message::pong(message.payload); ws_message_tx.send(message).unwrap(); } _ => ws_message_tx.send(message).unwrap(), } } }) .unwrap(); let _ = thread::Builder::new() .name("ws_send_loop".to_owned()) .spawn(move || { for message in message_rx.iter() { let message: Message = message; sender.send_message(&message) .or_else(|e| { match e { WebSocketError::IoError(e) => { match e.kind() { io::ErrorKind::BrokenPipe => Ok(()), _ => Err(e), } } _ => panic!(e), } }) .unwrap(); } }) .unwrap(); for markdown in markdown_receiver.iter() { message_tx.send(Message::text(markdown)).unwrap(); } } /// Starts the server. /// /// Returns a channel that can be used to send data that will be pushed to clients of the /// server. pub fn start(&mut self) -> chan::Sender<String> { // FIXME: Currently, this channel sends to the first available consumer, not to all. let (markdown_sender, markdown_receiver) = chan::sync(0); let server = self.server.try_clone().unwrap(); thread::spawn(move || { for connection in server.incoming() { let connection = connection.unwrap(); let markdown_receiver = markdown_receiver.clone(); thread::spawn(move || { Self::handle_connection(connection, markdown_receiver.clone()); }); } }); markdown_sender } } #[cfg(test)] mod tests { use websockets::{Client, Message, Receiver}; use websockets::client::request::Url; #[test] fn initial_send() { let mut server = super::Server::new("localhost:0"); let sender = server.start(); let url = Url::parse(&format!("ws://localhost:{}", server.local_addr().unwrap().port())) .unwrap(); let request = Client::connect(&url).unwrap(); let response = request.send().unwrap(); response.validate().unwrap(); let (_, mut receiver) = response.begin().split(); sender.send("Hello world!".to_owned()); let message: Message = receiver.recv_message().unwrap(); assert_eq!(String::from_utf8(message.payload.into_owned()).unwrap(), "Hello world!"); } #[test] fn multiple_send() { let mut server = super::Server::new("localhost:0"); let sender = server.start(); let url = Url::parse(&format!("ws://localhost:{}", server.local_addr().unwrap().port())) .unwrap(); let request = Client::connect(&url).unwrap(); let response = request.send().unwrap(); response.validate().unwrap(); let (_, mut receiver) = response.begin().split(); let mut messages = receiver.incoming_messages(); sender.send("Hello world!".to_owned()); let hello_message: Message = messages.next().unwrap().unwrap(); assert_eq!(String::from_utf8(hello_message.payload.into_owned()).unwrap(), "Hello world!"); sender.send("Goodbye world!".to_owned()); let goodbye_message: Message = messages.next().unwrap().unwrap(); assert_eq!(String::from_utf8(goodbye_message.payload.into_owned()).unwrap(), "Goodbye world!"); } } <file_sep>extern crate aurelius; extern crate websocket; extern crate url; use websocket::{Client, Message, Receiver}; use url::Url; use aurelius::Server; #[test] fn simple() { let mut server = Server::new(); let sender = server.start(); let websocket_port = server.websocket_addr().unwrap().port(); let url = Url::parse(&format!("ws://localhost:{}", websocket_port)).unwrap(); let request = Client::connect(url).unwrap(); let response = request.send().unwrap(); response.validate().unwrap(); let (_, mut receiver) = response.begin().split(); sender.send(String::from("Hello, world!")).unwrap(); let message: Message = receiver.incoming_messages().next().unwrap().unwrap(); let html: String = String::from_utf8(message.payload.into_owned()).unwrap(); assert_eq!(html.trim(), String::from("<p>Hello, world!</p>")); } <file_sep>//! Contains the HTTP server component. use std::collections::HashMap; use std::fs; use std::io; use std::net::{SocketAddr, ToSocketAddrs}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use porthole; use nickel::{self, Nickel, StaticFilesHandler}; use markdown; /// The HTTP server. /// /// The server listens on the provided port, rendering the markdown preview when a GET request is /// received at the server root. pub struct Server { local_addr: SocketAddr, /// The "current working directory" of the server. Any static file requests will be joined to /// this directory. cwd: Arc<Mutex<PathBuf>>, } impl Server { /// Creates a new server that listens on socket address `addr`. pub fn new<A, P>(addr: A, working_directory: P) -> Server where A: ToSocketAddrs, P: AsRef<Path> { let socket_addr = addr.to_socket_addrs() .unwrap() .map(|addr| { if addr.port() == 0 { let unused_port = porthole::open().unwrap(); format!("localhost:{}", unused_port) .to_socket_addrs() .unwrap() .next() .unwrap() } else { addr } }) .next() .unwrap(); Server { local_addr: socket_addr, cwd: Arc::new(Mutex::new(working_directory.as_ref().to_owned())), } } pub fn change_working_directory<P>(&mut self, dir: P) where P: AsRef<Path> { let mut cwd = self.cwd.lock().unwrap(); *cwd = dir.as_ref().to_owned(); } pub fn local_addr(&self) -> io::Result<SocketAddr> { Ok(self.local_addr) } fn listen(&self, websocket_port: u16, config: &::Config) { let mut server = Nickel::new(); server.options = nickel::Options::default().output_on_listen(false); let mut data = HashMap::new(); data.insert("websocket_port", websocket_port.to_string()); data.insert("initial_markdown", markdown::to_html(&config.initial_markdown)); data.insert("highlight_theme", config.highlight_theme.to_owned()); data.insert("custom_css", config.custom_css.to_owned()); let root = Path::new(env!("CARGO_MANIFEST_DIR")); let mut markdown_view = root.to_path_buf(); markdown_view.push("templates/markdown_view.html"); server.utilize(router! { get "/" => |_, response| { return response.render(markdown_view.to_str().unwrap(), &data); } }); let local_cwd = self.cwd.clone(); server.utilize(middleware! { |request, response| let path = request.path_without_query().map(|path| { path[1..].to_owned() }); if let Some(path) = path { let path = local_cwd.lock().unwrap().clone().join(path); match fs::metadata(&path) { Ok(ref attr) if attr.is_file() => return response.send_file(&path), Err(ref e) if e.kind() != io::ErrorKind::NotFound => { debug!("Error getting metadata for file '{:?}': {:?}", path, e) } _ => {} } }; }); let mut static_dir = root.to_path_buf(); static_dir.push("static"); assert!(static_dir.is_absolute()); server.utilize(StaticFilesHandler::new(static_dir.to_str().unwrap())); let listening = server.listen(self.local_addr).unwrap(); listening.detach(); } /// Starts the server. /// /// Once a connection is received, the client will initiate WebSocket connections on /// `websocket_port`. If `initial_markdown` is present, it will be displayed on the first /// connection. pub fn start(&self, websocket_port: u16, config: &::Config) { self.listen(websocket_port, &config); } } <file_sep>//! [aurelius](https://github.com/euclio/aurelius) is a complete solution for rendering and //! previewing markdown. //! //! This crate provides a server that can render and update an HTML preview of markdown without a //! client-side refresh. The server listens for both WebSocket and HTTP connections on arbitrary //! ports. Upon receiving an HTTP request, the server renders a page containing a markdown preview. //! Client-side JavaScript then initiates a WebSocket connection which allows the server to push //! changes to the client. //! //! This crate was designed to power [vim-markdown-composer], a markdown preview plugin for //! [Neovim](http://neovim.io), but it may be used to implement similar plugins for any editor. //! See [vim-markdown-composer] for a usage example. //! //! aurelius follows stable Rust. However, the API currently unstable and may change without //! warning. //! //! # Acknowledgments //! This crate is inspired by suan's //! [instant-markdown-d](https://github.com/suan/instant-markdown-d). //! //! # Why the name? //! "Aurelius" is a Roman *gens* (family name) shared by many famous Romans, including emperor //! <NAME>, one of the "Five Good Emperors." The gens itself originates from the Latin //! *aureus* meaning "golden." Also, tell me that "Markdown Aurelius" isn't a great pun. //! //! <cite>[Aurelia (gens) on Wikipedia](https://en.wikipedia.org/wiki/Aurelia_(gens))</cite>. //! //! [vim-markdown-composer]: https://github.com/euclio/vim-markdown-composer #![deny(missing_docs)] extern crate chan; extern crate hoedown; extern crate porthole; extern crate url; extern crate websocket as websockets; #[macro_use] extern crate log; #[macro_use] extern crate nickel; pub mod browser; pub mod markdown; mod http; mod websocket; use std::env; use std::net::SocketAddr; use std::io; use std::path::{Path, PathBuf}; use std::sync::mpsc::{self, Sender}; use std::thread; use http::Server as HttpServer; use websocket::Server as WebSocketServer; /// The `Server` type constructs a new markdown preview server. /// /// The server will listen for HTTP and WebSocket connections on arbitrary ports. pub struct Server { http_server: HttpServer, websocket_server: WebSocketServer, config: Config, } /// Configuration for the markdown server. #[derive(Debug, Clone)] pub struct Config { /// The initial markdown to render when starting the server. pub initial_markdown: String, /// The syntax highlighting theme to use. /// /// Defaults to the github syntax highlighting theme. pub highlight_theme: String, /// The directory that static files should be served out of. /// /// Defaults to the current working directory. pub working_directory: PathBuf, /// Custom CSS that should be used to style the markdown. /// /// Defaults to the github styles. pub custom_css: String, } impl Default for Config { fn default() -> Self { Config { working_directory: env::current_dir().unwrap().to_owned(), initial_markdown: "".to_owned(), highlight_theme: "github".to_owned(), custom_css: "/vendor/github-markdown-css/github-markdown.css".to_owned(), } } } impl Server { /// Creates a new markdown preview server. pub fn new() -> Server { Self::new_with_config(Config { ..Default::default() }) } /// Creates a new configuration with the config struct. /// /// # Example /// ``` /// use std::default::Default; /// use aurelius::{Config, Server}; /// /// let server = Server::new_with_config(Config { /// highlight_theme: "github".to_owned(), .. Default::default() /// }); /// ``` pub fn new_with_config(config: Config) -> Server { Server { http_server: HttpServer::new(("localhost", 0), config.working_directory.clone()), websocket_server: WebSocketServer::new(("localhost", 0)), config: config, } } /// Returns the socket address that the websocket server is listening on. pub fn websocket_addr(&self) -> io::Result<SocketAddr> { self.websocket_server.local_addr() } /// Returns the socket address that the HTTP server is listening on. pub fn http_addr(&self) -> io::Result<SocketAddr> { self.http_server.local_addr() } /// Changes the "current working directory" of the HTTP server. The HTTP server will serve /// static file requests out of the new directory. pub fn change_working_directory<P>(&mut self, dir: P) where P: AsRef<Path> { self.http_server.change_working_directory(dir); } /// Starts the server. /// /// Returns a channel that can be used to send markdown to the server. The markdown will be /// sent as HTML to all clients of the websocket server. pub fn start(&mut self) -> Sender<String> { let (markdown_sender, markdown_receiver) = mpsc::channel::<String>(); let websocket_sender = self.websocket_server.start(); thread::spawn(move || { for markdown in markdown_receiver.iter() { let html: String = markdown::to_html(&markdown); websocket_sender.send(html); } }); let websocket_port = self.websocket_server.local_addr().unwrap().port(); debug!("Starting http_server"); self.http_server.start(websocket_port, &self.config); markdown_sender } } #[cfg(test)] mod tests { use super::Server; #[test] fn sanity() { let mut server = Server::new(); server.start(); } } <file_sep>[package] name = "aurelius" version = "0.1.12" authors = ["<NAME> <<EMAIL>>"] description = "A complete solution for previewing markdown." documentation = "https://euclio.github.io/aurelius" homepage = "https://github.com/euclio/aurelius" repository = "https://github.com/euclio/aurelius" readme = "README.md" keywords = ["markdown", "vim"] license = "MIT/Apache-2.0" [dependencies] chan = "0.1.14" hoedown = "5.0.0" log = "0.3.1" nickel = { version = "0.8.1", git = "https://github.com/nickel-org/nickel.rs" } porthole = "0.1.0" url = "1.1.0" websocket = "~0.17.0" [dev-dependencies] hyper = "0.9.4" <file_sep>extern crate aurelius; extern crate hyper; extern crate url; use std::default::Default; use std::io::prelude::*; use hyper::Client; use url::Url; use aurelius::{Config, Server}; fn get_basic_response(server: &Server) -> String { let http_addr = server.http_addr().unwrap(); let url = Url::parse(&format!("http://localhost:{}", http_addr.port())).unwrap(); let mut res = Client::new().get(url).send().unwrap(); let mut body = String::new(); res.read_to_string(&mut body).unwrap(); body } #[test] fn custom_css() { let url = "http://scholarlymarkdown.com/scholdoc-distribution/css/core/scholmd-core-latest.css"; let mut server = Server::new_with_config(Config { custom_css: String::from(url), ..Default::default() }); server.start(); let response = get_basic_response(&server); assert!(response.contains(url)); } #[test] fn highlight_theme() { let mut server = Server::new_with_config(Config { highlight_theme: String::from("darcula"), ..Default::default() }); server.start(); let response = get_basic_response(&server); let link = "/vendor/highlight.js/styles/darcula.css"; assert!(response.contains(link)); } <file_sep>//! Functions for rendering markdown. use hoedown::renderer::html; use hoedown::{Markdown, Render}; use hoedown::{AUTOLINK, FENCED_CODE, TABLES}; /// Renders a markdown string to an HTML string. /// /// This function enables the following extensions: /// /// - Autolinking email addresses and URLs /// - Fenced code blocks /// - Tables pub fn to_html(markdown: &str) -> String { let doc = Markdown::new(markdown).extensions(AUTOLINK | FENCED_CODE | TABLES); let mut html = html::Html::new(html::Flags::empty(), 0); html.render(&doc).to_str().unwrap().to_string() }
223d260f0cceedf9c65face17ef2130e75c512ad
[ "TOML", "Rust" ]
9
Rust
PaulDebus/aurelius
06c3ef8718786424730bbb8dbb5e2416a5373e4e
7990603e9881e2f07775738501fb1b39fdda2d31
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Student(models.Model): name = models.CharField(max_length=15) email = models.EmailField(unique=True) subject = models.CharField(max_length=30) class Meta: db_table = 'student' verbose_name = 'student' verbose_name_plural = 'student' <file_sep># Generated by Django 2.2.7 on 2019-11-15 17:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('caapp', '0002_auto_20191115_1747'), ] operations = [ migrations.AlterModelOptions( name='student', options={'verbose_name': 'student'}, ), ] <file_sep># consultadd-assignments in Develop branch <file_sep>from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .forms import UserRegistrationForm def registration(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') messages.success(request, f'Your account has ben created! Login to access the blog!') return redirect('login') else: form = UserRegistrationForm() return render(request, 'users/registration.html', {'form': form}) <file_sep>from django import forms from django.core import validators def validate(password): special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]" if not any(char.isdigit() for char in password): raise forms.ValidationError('Password must contain at least 1 digit.') if not any(char.isalpha() for char in password): raise forms.ValidationError('Password must contain at 1 least letter.') if not any(char in special_characters for char in password): raise forms.ValidationError('Password must contain at least 1 special character.') class signupForm(forms.Form): name = forms.CharField(label="Enter Name", max_length=50) email = forms.EmailField(label="Enter Email", max_length=50) password = forms.CharField(label="Enter Password", widget=forms.PasswordInput, validators=[validate]) <file_sep>from django.http import HttpResponse from django.shortcuts import render from . import signup_form def signup(request): form = signup_form.signupForm if request.method == "POST": form = signup_form.signupForm(request.POST) if form.is_valid(): print('NAME = ', form.cleaned_data['name']) print('EMAIL = ', form.cleaned_data['email']) print('PASSWORD = ', form.cleaned_data['password']) return render(request, 'signup.html', {'form': form}) def home(request): return render(request, 'index.html') <file_sep>from django.contrib import admin from caapp.models import Student # Register your models here. admin.site.register(Student) <file_sep># Generated by Django 2.2.7 on 2019-11-15 17:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('caapp', '0001_initial'), ] operations = [ migrations.AlterModelTable( name='student', table='student', ), ]
66cfa4e62a2999409364137f0f2f33fe78ccde8b
[ "Markdown", "Python" ]
8
Python
avithekkc/consultadd-assignment
a897812b45fa0263fd6cb23cc220d5ac19f78f8e
d847a6eb79cdea74f1b69963c69bf8a0f2ef2a7b
refs/heads/main
<file_sep># Mongo Export Surgeon [![Docker Image CI](https://github.com/tehKapa/mongoexportsurgeon/actions/workflows/docker-image.yml/badge.svg)](https://github.com/tehKapa/mongoexportsurgeon/actions/workflows/docker-image.yml) An easy way to export documents associated with an ID from multiple collections. Surgically. ## Build ``` docker build -t tehkapa/mongoexportsurgeon . ``` ## Run ``` docker run --name mongoes -it \ -e DBNAME=database \ -e USERNAME=user \ -e PASSWORD=<PASSWORD> \ -e HOST=mongo-server \ -e AWSACCESSKEYID=AKxxxxxx \ -e AWSSECRETACCESSKEY=<KEY> \ -e BUCKET=my-bucket \ tehkapa/mongoexportsurgeon ``` or using .env file ``` docker run --name mongoes --env-file .env -it tehkapa/mongoexportsurgeon ``` You can pass organizationID on run command with `--env ID=ac12cd3ef45 --env KEY=organization` <file_sep>DBNAME=database USERNAME=user PASSWORD=<PASSWORD> HOST=localhost AWSACCESSKEYID=<KEY> AWSSECRETACCESSKEY=Sxxxxxxxx BUCKET=bucket KEY=organization <file_sep>FROM alpine:3.9 RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/main' >> /etc/apk/repositories RUN echo 'http://dl-cdn.alpinelinux.org/alpine/v3.9/community' >> /etc/apk/repositories RUN apk update && apk --no-cache --update add \ bash \ curl \ ca-certificates \ mongodb-tools \ mongodb \ python3 \ htop \ py3-pip \ && pip3 install --upgrade pip \ && pip3 install \ awscli \ && rm -rf /var/cache/apk/* ENV PROJECT_WORKDIR=/home/mongo WORKDIR $PROJECT_WORKDIR/ COPY . $PROJECT_WORKDIR/ RUN chmod +x $PROJECT_WORKDIR/mongoexport.sh CMD [ "./mongoexport.sh" ] <file_sep>#!/bin/bash set -e # Declare connection variable dbname=$DBNAME username=$USERNAME password=$<PASSWORD> host=$HOST idValue=$ID keyField=$KEY bucket=$BUCKET aws_access_key_id=$AWSACCESSKEYID aws_secret_access_key=$AWSSECRETACCESSKEY mongo --quiet "mongodb+srv://$username:$password@$host/$dbname" --eval "db.stats();" RESULT=$? # returns 0 if mongo eval succeeds if [ $RESULT -ne 0 ]; then echo "Can't connect to MongoDB server" exit 1 break else collections=$(mongo --quiet "mongodb+srv://$username:$password@$host/$dbname" --eval 'rs.slaveOk();db.getCollectionNames().join(" ");' | tail -1) IFS=', ' read -r -a collectionArray <<<"$collections" echo "Connected to $host @ $dbname with $username" echo " " exportDate=$(date -Iseconds) aws configure set aws_access_key_id $aws_access_key_id aws configure set aws_secret_access_key $aws_secret_access_key fi while true; do unset idValue unset keyField if [ -z "$keyField" ]; then echo "Enter Field to export (tenant, organization, group, etc.):" read keyField fi if [ -z "$idValue" ]; then echo "Enter ID value to export:" read idValue fi mkdir -p $PWD/$idValue/$exportDate for ((i = 0; i < ${#collectionArray[@]}; ++i)); do echo "Exporting $idValue from collection ${collectionArray[$i]}" mongoexport --uri="mongodb+srv://$username:$password@$host/$dbname" --collection ${collectionArray[$i]} --query="{\"$keyField\": {\"\$oid\": \"$idValue\"}}" --out $PWD/$idValue/$exportDate/${collectionArray[$i]}.json aws s3 cp $PWD/$idValue/$exportDate/${collectionArray[$i]}.json s3://$bucket/$idValue/$exportDate/${collectionArray[$i]}.json echo "${collectionArray[$i]} collection exported." done echo "Done. All collections have been exported here s3://$bucket/$idValue/$exportDate/" echo "Export another value of $keyField? [y/n] :" read response if [ "$response" != "y" ]; then break fi done
43a8a54e6531c38cd529315012e6de29078dd327
[ "Markdown", "Dockerfile", "Shell" ]
4
Markdown
tehKapa/mongoexportsurgeon
a605ba4e8392d84d7eea8d495864f91d0c6461b6
114b39160b14b21caba915c793c08824b64d8c68
refs/heads/master
<file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmBookingReports : System.Web.UI.Page { clsReports objReport = new clsReports(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { DisplayBookingReport(); } } public void DisplayBookingReport() { DataSet dsBook = objReport.DisplayBookingReport(); if (dsBook.Tables[0].Rows.Count > 0) { Gvboooking.DataSource = dsBook.Tables[0]; Gvboooking.DataBind(); } } protected void Gvboooking_PageIndexChanging(object sender, GridViewPageEventArgs e) { Gvboooking.PageIndex = e.NewPageIndex; DisplayBookingReport(); } protected void btnExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); Gvboooking.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } protected void btnPdf_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.pdf"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/pdf"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); Gvboooking.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for clsVehicle /// </summary> public class clsVehicle { public clsVehicle() { // // TODO: Add constructor logic here // } string vehicleId; public string VehicleId { get { return vehicleId; } set { vehicleId = value; } } public DataSet GetVehicleDetails() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@VechicleId", VehicleId); p[0].SqlDbType = SqlDbType.VarChar; return SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure,"spDisplayVehicleById",p); } public DataSet GetVehicleId() { string SqlStat = "Select vehicleId from tblVehicle"; return SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, SqlStat); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; public partial class Admin_frmfeedback : System.Web.UI.Page { SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=vehicle;Persist Security Info=True;User ID=sa;Password=abc"); protected void Page_Load(object sender, EventArgs e) { SqlDataAdapter da = new SqlDataAdapter("select * from feedback",con); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds; GridView1.DataBind(); } }<file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmAdminBookingsDisplay : System.Web.UI.Page { ClsAdminBookings obj = new ClsAdminBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.DisplayConformBookings(); GridBookingRec.DataSource = ds.Tables[0]; GridBookingRec.DataBind(); } } protected void GridCancelRec_Sorting(object sender, GridViewSortEventArgs e) { DataSet ds = obj.DisplayCanelSorting("select * from tblbookinginfo where BookingStatus=0 order by BookingId"); GridBookingRec.DataSource = ds.Tables[0]; GridBookingRec.DataBind(); } protected void GridCancelRec_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridBookingRec.PageIndex = e.NewPageIndex; DataSet ds = obj.DisplayConformBookings(); GridBookingRec.DataSource = ds.Tables[0]; GridBookingRec.DataBind(); } protected void BtnCancelRec_Click(object sender, EventArgs e) { Response.Redirect("frmAdminBookingCancelDisplay.aspx"); } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmHome.aspx"); } public int Sum() { int i; i = obj.DisplayTotalAmount("select sum(BookingAmount) from tblbookinginfo where BookingStatus=0"); return i; } protected void GridBookingRec_RowCommand(object sender, GridViewCommandEventArgs e) { ClsUserBookings obj1 = new ClsUserBookings(); int id = Convert.ToInt32(e.CommandArgument.ToString()); obj1.UpdateBookingInfo("update tblBookingInfo set BookingStatus=2 where BookingId="+id); DataSet ds = obj.DisplayConformBookings(); GridBookingRec.DataSource = ds.Tables[0]; GridBookingRec.DataBind(); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmList : System.Web.UI.Page { ClsAdmin obj = new ClsAdmin(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { GetData(); } } public void GetData() { DataSet ds = obj.DisplayVehicles("select * from tblvehicle"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("frmVehicleAdd.aspx"); } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("frmUpdate.aspx"); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsEmployee /// </summary> public class ClsEmployee { public ClsEmployee() { // // TODO: Add constructor logic here // } string _EmpName, _Surname, _Address, _City, _State, _JobDesc; public string JobDesc { get { return _JobDesc; } set { _JobDesc = value; } } public string State { get { return _State; } set { _State = value; } } public string City { get { return _City; } set { _City = value; } } public string Address { get { return _Address; } set { _Address = value; } } public string Surname { get { return _Surname; } set { _Surname = value; } } public string EmpName { get { return _EmpName; } set { _EmpName = value; } } int _EmpId, _WorkOnVehicle, _ZipCode; public int ZipCode { get { return _ZipCode; } set { _ZipCode = value; } } public int WorkOnVehicle { get { return _WorkOnVehicle; } set { _WorkOnVehicle = value; } } public int EmpId { get { return _EmpId; } set { _EmpId = value; } } float _Salary; public float Salary { get { return _Salary; } set { _Salary = value; } } public void InsertEmployee() { SqlParameter[] p = new SqlParameter[9]; p[0] = new SqlParameter("@Ename", SqlDbType.VarChar ); p[0].Value = _EmpName ; p[1] = new SqlParameter("@Surname", SqlDbType.VarChar ); p[1].Value = _Surname; p[2] = new SqlParameter("@Address", SqlDbType.VarChar ); p[2].Value = _Address; p[3] = new SqlParameter("@City", SqlDbType.VarChar); p[3].Value = _City ; p[4] = new SqlParameter("@State", SqlDbType.VarChar); p[4].Value = _State ; p[5] = new SqlParameter("@ZipCode", SqlDbType.Float); p[5].Value = _ZipCode ; p[6] = new SqlParameter("@WorkOnVehicle", SqlDbType.Int); p[6].Value = _WorkOnVehicle ; p[7] = new SqlParameter("@Salary", SqlDbType.Float); p[7].Value = _Salary; p[8]=new SqlParameter ("@JobDesc",SqlDbType.VarChar ); p[8].Value = _JobDesc; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Insert_Employee", p); } public DataSet DisplyEmployee(string Stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, Stat); return ds; } public void UpdateEmployee() { SqlParameter[] p = new SqlParameter[10]; p[0] = new SqlParameter("@EmpId", SqlDbType.Int); p[0].Value = _EmpId; p[1] = new SqlParameter("@Ename", SqlDbType.VarChar); p[1].Value = _EmpName; p[2] = new SqlParameter("@Surname", SqlDbType.VarChar); p[2].Value = _Surname; p[3] = new SqlParameter("@Address", SqlDbType.VarChar); p[3].Value = _Address; p[4] = new SqlParameter("@City", SqlDbType.VarChar); p[4].Value = _City; p[5] = new SqlParameter("@State", SqlDbType.VarChar); p[5].Value = _State; p[6] = new SqlParameter("@ZipCode", SqlDbType.Float); p[6].Value = _ZipCode; p[7] = new SqlParameter("@WorkOnVehicle", SqlDbType.Int); p[7].Value = _WorkOnVehicle; p[8] = new SqlParameter("@Salary", SqlDbType.Float); p[8].Value = _Salary; p[9] = new SqlParameter("@JobDesc", SqlDbType.VarChar); p[9].Value = _JobDesc; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Update_Employee", p); } public void DeleteEmployee() { SqlParameter p = new SqlParameter("@EmpId", SqlDbType.Int); p.Value = _EmpId; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Delete_Employee", p); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmUpdate : System.Web.UI.Page { ClsAdmin obj = new ClsAdmin(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { ClsAdminBookings VehicleObj = new ClsAdminBookings(); DataSet ds = VehicleObj.DiplayVehicleaId("select VehicleId from tblVehicle"); DdlVehicleId.Items.Clear(); DdlVehicleId.Items.Insert(0, "Select"); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { DdlVehicleId.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } } } protected void DdlVehicleId_SelectedIndexChanged(object sender, EventArgs e) { GetData(); } public void GetData() { DataSet ds = obj.DisplayVehicles("select * from tblvehicle where VehicleId='"+DdlVehicleId.SelectedItem.ToString ()+"'"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; GetData(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; GetData(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { TextBox t1, t2, t3, t4, t5, t6; t1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtVehicleId"); t2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtDescription"); t3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtModel"); t4 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtMake"); t5 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtVehicleType"); t6 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtRate"); obj.VehicleId = t1.Text; obj.Description = t2.Text; obj.Model = t3.Text; obj.Make = t4.Text; obj.VehicleType = Convert.ToInt16 (t5.Text); obj.RatePerDay = Convert.ToInt16(t6.Text); obj.UpdateVehicle(); GridView1.EditIndex = -1; GetData(); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { Label l1; l1 = (Label)GridView1.Rows[e.RowIndex].FindControl("LblVehicleId"); obj.VehicleId = l1.Text; obj.DeleteVehicle(); GridView1.EditIndex = -1; GetData(); } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmEmployeeUpdation : System.Web.UI.Page { ClsEmployee obj = new ClsEmployee(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { GetData(); } } public void GetData() { DataSet ds = obj.DisplyEmployee("select * from tblEmployeeInfo"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; GetData(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; GetData(); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridView1.PageIndex = e.NewPageIndex; GetData(); } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { DataSet ds = obj.DisplyEmployee("select * from tblEmployeeInfo order by " + e.SortExpression); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { TextBox t1; t1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtEmpno"); Response.Redirect("frmAdminModifyEmp.aspx?EmpId=" + t1.Text); } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { Label l1; l1 = (Label)GridView1.Rows[e.RowIndex].FindControl("LblEmpNo"); Response.Redirect("frmEmployeeDelation.aspx?EmpId=" + l1.Text); } protected void BtnCancel_Click(object sender, EventArgs e) { Response.Redirect("frmEmployeeInfo.aspx"); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsAdmin /// </summary> public class ClsAdmin { public ClsAdmin() { // // TODO: Add constructor logic here // } string _VehicleId, _Description, _Model, _Make; public string Make { get { return _Make; } set { _Make = value; } } public string Model { get { return _Model; } set { _Model = value; } } public string Description { get { return _Description; } set { _Description = value; } } public string VehicleId { get { return _VehicleId; } set { _VehicleId = value; } } int _VehicleType; public int VehicleType { get { return _VehicleType; } set { _VehicleType = value; } } float _RatePerDay; public float RatePerDay { get { return _RatePerDay; } set { _RatePerDay = value; } } public void AddVehicle() { SqlParameter[] p = new SqlParameter[6]; p[0] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[0].Value = _VehicleId; p[1] = new SqlParameter("@Description", SqlDbType.VarChar); p[1].Value = _Description; p[2] = new SqlParameter("@Model", SqlDbType.VarChar); p[2].Value = _Model; p[3] = new SqlParameter("@Make", SqlDbType.VarChar); p[3].Value = _Make; p[4] = new SqlParameter("@vehicletype", SqlDbType.Int); p[4].Value = _VehicleType; p[5] = new SqlParameter("@RatePerDay", SqlDbType.Float); p[5].Value = _RatePerDay; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure , "Insert_vehicle", p); } public DataSet DisplayVehicles(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public void UpdateVehicle() { SqlParameter[] p = new SqlParameter[6]; p[0] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[0].Value = _VehicleId; p[1] = new SqlParameter("@Description", SqlDbType.VarChar); p[1].Value = _Description; p[2] = new SqlParameter("@Model", SqlDbType.VarChar); p[2].Value = _Model; p[3] = new SqlParameter("@Make", SqlDbType.VarChar); p[3].Value = _Make; p[4] = new SqlParameter("@vehicletype", SqlDbType.Int); p[4].Value = _VehicleType; p[5] = new SqlParameter("@RatePerDay", SqlDbType.Float); p[5].Value = _RatePerDay; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "update_vehicle", p); } public void DeleteVehicle() { SqlParameter p = new SqlParameter("@VehicleId", SqlDbType.VarChar); p.Value = _VehicleId; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "delete_vehicle", p); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmPackageBook : System.Web.UI.Page { ClsPackage obj = new ClsPackage(); ClsAdminBookings obj1 = new ClsAdminBookings(); ClsUserBookings uid = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.DiplayPackageId("select PackageId from tblPakageInfo"); DdlPackageId.Items.Clear(); DdlPackageId.Items.Insert(0, "Select"); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { DdlPackageId.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } DataSet ds1 = obj1.DiplayVehicleaId("select VehicleId from tblVehicle"); DdlVehicleId.Items.Clear(); DdlVehicleId.Items.Insert(0, "Select"); for (int i = 0; i <= ds1.Tables[0].Rows.Count - 1; i++) { DdlVehicleId.Items.Add(ds1.Tables[0].Rows[i][0].ToString()); } } } protected void DdlPackageId_SelectedIndexChanged(object sender, EventArgs e) { if (DdlPackageId.SelectedItem.Text != null) { obj.PackageId = Convert.ToInt32(DdlPackageId.SelectedItem.Text); obj.DisplayPackage(); TxtDetails.Text =obj.Details.ToString (); TxtNoOfDays.Text =obj.NoOfDays.ToString (); TxtPrice .Text =obj.Price.ToString (); TxtUserName.Text = Session["User"].ToString(); DataSet ds = uid.DiplayUserId("select UserId from tblUserRegistration where UserName='" + TxtUserName.Text + "'"); TxtUseID.Text = ds.Tables[0].Rows[0][0].ToString(); } } protected void BtnBooking_Click(object sender, EventArgs e) { obj.PackageId = Convert.ToInt32 (DdlPackageId.SelectedItem.Text); obj.DateOfBook = TxtBookingDate.Text; obj.VehicleId = DdlVehicleId.SelectedItem.Text; obj.UserId = Convert.ToInt16 (TxtUseID.Text); obj.BookPackage(); Response.Redirect("frmPackageConformation.aspx"); //LblMessage.Visible = true; //LblMessage.Text = "Package Conformed Happy Journey.."; } protected void BtnCancel_Click(object sender, EventArgs e) { GetData(); } public void GetData() { TxtDetails.Text = ""; TxtUseID.Text = ""; TxtPrice.Text = ""; TxtNoOfDays.Text = ""; TxtBookingDate.Text = ""; DdlVehicleId.SelectedIndex=0; DdlPackageId.SelectedIndex=0; DdlAmountPaid.SelectedIndex = 0; } protected void BtnBack_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmVehicleBooking : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.DiplayVehicleaId ("select VehicleId from tblVehicle"); DdlVehicleId.Items.Clear(); DdlVehicleId.Items.Insert(0, "Select"); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { DdlVehicleId.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } } } protected void DdlVehicleId_SelectedIndexChanged(object sender, EventArgs e) { if (DdlVehicleId .SelectedItem.Text != "Select") { //ClearData(); obj.VehicleId = DdlVehicleId.SelectedItem.Text; obj.DisplyVehicleInfo(); TxtDescription.Text = obj.Description; TxtModel.Text = obj.Model; TxtManuFacturer.Text = obj.Make; TxtRatePerDay.Text = obj.RatePerDay.ToString(); TxtVehicleType.Text= obj.VehicleType.ToString(); TxtUserName .Text = Session["User"].ToString(); DataSet ds = obj.DiplayUserId("select UserId from tblUserRegistration where UserName='" + TxtUserName.Text + "'"); TxtUserId.Text = ds.Tables[0].Rows[0][0].ToString(); //TxtBookingStatus.Text =obj.BookingStatus .ToString (); } else ClearData(); } public void ClearData() { TxtUserName.Text = ""; TxtUserId.Text = ""; TxtDescription.Text = ""; TxtManuFacturer.Text = ""; TxtModel.Text = ""; TxtVehicleType.Text = ""; TxtRatePerDay.Text = ""; TxtNoOfDays.Text = ""; TxtBookingDate.Text = ""; DdlVehicleId.SelectedIndex = 0; TxtDescription.Focus(); } protected void BtnCancel_Click(object sender, EventArgs e) { ClearData(); } protected void BtnBooking_Click(object sender, EventArgs e) { obj.DateOfBooked = TxtBookingDate.Text; obj.VehicleId = DdlVehicleId.SelectedItem.Text; obj.TimeOfPeriod = int.Parse (TxtNoOfDays .Text); obj.AmountPaid = DdlAmountPaid.SelectedItem.Text; obj.UserId = int.Parse (TxtUserId.Text); obj.AcceptBooking(); if (DdlAmountPaid.SelectedItem.Text == "CreditCard") { // DataSet ds = obj.GetBookingId("Select BookingAmount from tblBookingInfo where BookingId =(select Max(BookingId) from tblBookingInfo)"); // Response.Redirect("frmAmountPaid.aspx?BookingAmount=" + ds.Tables[0].Rows[0][0].ToString()); //} //else //{ DataSet ds = obj.GetBookingId("Select Max(BookingId) from tblBookingInfo"); Response.Redirect("frmBookingDisplay.aspx?BookingId=" + ds.Tables[0].Rows[0][0].ToString()+"&Text=Processing Wait...."); } } protected void DdlAmountPaid_SelectedIndexChanged(object sender, EventArgs e) { } protected void BtnBack_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmCancelReport : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } ClsUserBookings obj = new ClsUserBookings(); if (!IsPostBack) { if (Request["id"] != null) { int i = Convert.ToInt16(Request["id"]); int BookId = Convert.ToInt16(Request["BookingId"]); if (i == 1) { obj.BookingId =BookId ; DataSet ds= obj.DisplayCancelBooking (); GridConform.DataSource =ds.Tables [0]; GridConform.DataBind (); } if (i == -1) { LblMessage.Visible = true; LblMessage.Text = "BookingId="+BookId .ToString ()+" Already Cancelled"; } } } } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsBookings /// </summary> public class ClsAdminBookings { public ClsAdminBookings() { // // TODO: Add constructor logic here // } int _BookingId, _UserId, _TimeOfPeriod, _BookingStatus; string _AmountPaid; public string AmountPaid { get { return _AmountPaid; } set { _AmountPaid = value; } } public int BookingStatus { get { return _BookingStatus; } set { _BookingStatus = value; } } public int TimeOfPeriod { get { return _TimeOfPeriod; } set { _TimeOfPeriod = value; } } public int UserId { get { return _UserId; } set { _UserId = value; } } public int BookingId { get { return _BookingId; } set { _BookingId = value; } } string _DateOfBooked, _VehicleId; public string VehicleId { get { return _VehicleId; } set { _VehicleId = value; } } public string DateOfBooked { get { return _DateOfBooked; } set { _DateOfBooked = value; } } float _BookingAmount; public float BookingAmount { get { return _BookingAmount; } set { _BookingAmount = value; } } public int ShowBookingInfo() { SqlParameter p = new SqlParameter("@VehicleId", SqlDbType.VarChar); p.Value = _VehicleId; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "DisplayBooking", p); DataRowCollection rec = ds.Tables[0].Rows; if (rec.Count > 0) { _BookingId = Convert.ToInt16(rec[0]["BookingId"]); _DateOfBooked = rec[0]["DateOfBooked"].ToString(); _VehicleId = rec[0]["VehicleId"].ToString(); _UserId = Convert.ToInt16(rec[0]["UserId"]); _TimeOfPeriod = Convert.ToInt16(rec[0]["TimePeriod"]); _BookingAmount = Convert.ToInt32(rec[0]["BookingAmount"]); _AmountPaid = rec[0]["AmountPaid"].ToString(); _BookingStatus = Convert.ToInt16(rec[0]["BookingStatus"]); return 1; } else return 0; } public DataSet DiplayVehicleaId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text , stat); return ds; } public DataSet DisplayBookingPackgeInfo(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet DisplayCancelBookings() { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "AdminBookingCancelDiplay"); return ds; } public DataSet DisplayCanelSorting(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text ,stat); return ds; } public DataSet DisplayConformBookings() { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "AdminBookingConformDiplay"); return ds; } public int DisplayTotalAmount(string stat) { int i = 0; i = Convert.ToInt32 (SqlHelper.ExecuteScalar(ClsConnection.GetConnection(), CommandType.Text, stat)); return i; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmAdminLogint : System.Web.UI.Page { ClsLogin obj = new ClsLogin(); bool Found; protected void Page_Load(object sender, EventArgs e) { TxtUserName.Focus(); } protected void BtnLogin_Click(object sender, EventArgs e) { if (TxtUserName.Text != "" && TxtPassWord.Text != "") { obj.UserName = TxtUserName.Text; obj.PassWord = <PASSWORD>; Found = obj.ValiDateUser(); if (Found == true) { Session["Admin"] = obj.UserName; Response.Redirect("frmHome.aspx"); } else Label1.Text = "InValid UserName/Password Try Again...."; } else Label1.Text = "Must Enter UserName and PassWord"; } protected void BtnCancel_Click(object sender, EventArgs e) { TxtUserName.Text = ""; TxtPassWord.Text = ""; TxtUserName.Focus(); } protected void LnkNewUser_Click(object sender, EventArgs e) { Response.Redirect("frmEmployeeRegistration.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmRegistration : System.Web.UI.Page { ClsUserRegistration obj = new ClsUserRegistration(); protected void Page_Load(object sender, EventArgs e) { } protected void BtnRegister_Click(object sender, EventArgs e) { obj.UserName = TxtName.Text; obj.Surname = TxtSurName.Text; obj.EmailId = TxtEmaiId.Text; obj.MobileNo =TxtMobileNo.Text; obj.Address = TxtAddress.Text; obj.City = DdlCity.SelectedItem.Text; obj.State = DdlState.SelectedItem.Text; obj.ZipCode =TxtZipCode.Text; obj.InsertUserRegistration(); ClsCustomerLogin LoginObj = new ClsCustomerLogin(); LoginObj.UserName = TxtName.Text; LoginObj.PassWord = <PASSWORD>; LoginObj.HintQuestion = DdlHintQuestion.SelectedItem.Text; LoginObj.Answer = TxtAnswer.Text; LoginObj.InsertUserLogn(); } protected void BtnCancel_Click(object sender, EventArgs e) { TxtName.Text = ""; TxtSurName.Text = ""; TxtPassWord.Text = ""; TxtMobileNo.Text = ""; TxtEmaiId.Text = ""; TxtAnswer.Text = ""; TxtAddress.Text = ""; TxtZipCode.Text = ""; DdlCity.SelectedIndex = 0; DdlState.SelectedIndex = 0; DdlHintQuestion.SelectedIndex = 0; } protected void LnkLogin_Click(object sender, EventArgs e) { Response.Redirect("~/frmLogin.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmAmountPaid : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.GetBookingAmount("select BookingAmount from tblBookingInfo where BookingId=" + Request["BookingId"]); TxtBookingAmount.Text = ds.Tables[0].Rows[0][0].ToString(); TxtUserName.Text = Session["User"].ToString(); } } protected void BtnOk_Click(object sender, EventArgs e) { Response.Redirect("frmConfirmation.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmConfirmation : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { if (Request["BookingId"] == null) { DataSet ds = obj.GetBookingId("select Max(BookingId) from tblBookingInfo"); LblBookingId.Text = "Booking TransId : " + ds.Tables[0].Rows[0][0].ToString(); LblUserName.Text = "UserName: " + Session["User"].ToString(); LblMessage.Text = "Congrats, Your Booking is Successful!.."; } else { LblBookingId.Text = "Booking TransId : " + Request["BookingId"]; LblUserName.Text = "UserName: " + Session["User"].ToString(); LblMessage.Text = " New Date of Journey :" + Request["Date"].ToString(); } } } protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmDriverInfo : System.Web.UI.Page { ClsEmployee obj = new ClsEmployee(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { GetData(); } } public void GetData() { DataSet ds = obj.DisplyEmployee ("select * from tblEmployeeInfo"); GridEmployee.DataSource = ds.Tables[0]; GridEmployee.DataBind(); } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("frmEmployeeUpdation.aspx"); } protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridEmployee.PageIndex = e.NewPageIndex; GetData(); } protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { DataSet ds = obj.DisplyEmployee("select * from tblEmployeeInfo order by " + e.SortExpression); GridEmployee.DataSource = ds.Tables[0]; GridEmployee.DataBind(); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmAdminPackage : System.Web.UI.Page { ClsAdminBookings obj = new ClsAdminBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { GetData(); } } protected void GridPackage_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridPackage.PageIndex = e.NewPageIndex; GetData(); } public void GetData() { DataSet ds = obj.DisplayBookingPackgeInfo("select * from tblPackageBookings"); GridPackage.DataSource = ds.Tables[0]; GridPackage.DataBind(); } protected void GridPackage_Sorting(object sender, GridViewSortEventArgs e) { DataSet ds = obj.DisplayBookingPackgeInfo("select * from tblPackageBookings order by " + e.SortExpression); GridPackage.DataSource = ds.Tables[0]; GridPackage.DataBind(); } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmHome.aspx"); } public int Sum() { int i; i = obj.DisplayTotalAmount ("select sum(PackagePrice) from tblPackageBookings"); return i; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for UserBookings /// </summary> public class ClsUserBookings { public ClsUserBookings() { // // TODO: Add constructor logic here // } string _VehicleId, _Description, _Model, _Make, _DateOfBooked, _AmountPaid; public string Description { get { return _Description; } set { _Description = value; } } public string AmountPaid { get { return _AmountPaid ; } set { _AmountPaid = value; } } public string DateOfBooked { get { return _DateOfBooked ; } set { _DateOfBooked = value; } } public string VehicleId { get { return _VehicleId; } set { _VehicleId = value; } } public string Model { get { return _Model ; } set { _Model = value; } } public string Make { get { return _Make ; } set { _Make = value; } } public int VehicleType { get { return _VehicleType; } set { _VehicleType = value; } } public int UserId { get { return _UserId ; } set { _UserId = value; } } public int BookingStatus { get { return _BookingStatus ; } set { _BookingStatus = value; } } public int TimeOfPeriod { get { return _TimeOfPeriod ; } set { _TimeOfPeriod = value; } } public int BookingId { get { return _BookingId; } set { _BookingId = value; } } public float RatePerDay { get { return _RatePerDay ; } set { _RatePerDay = value; } } public float BookingAmount { get { return _BookingAmount ; } set { _BookingAmount = value; } } int _VehicleType, _BookingStatus, _UserId, _TimeOfPeriod, _BookingId; float _RatePerDay, _BookingAmount; public DataSet DiplayVehicleaId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public void DisplyVehicleInfo() { SqlParameter p = new SqlParameter("@VehicleId", SqlDbType.VarChar); p.Value = _VehicleId; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "DisplayVehicleAvaliability", p); DataRowCollection rec = ds.Tables[0].Rows; if (rec.Count > 0) { _Description = rec[0]["Description"].ToString(); _Model = rec[0]["Model"].ToString(); _Make = rec[0]["Make"].ToString(); _VehicleType = Convert.ToInt32(rec[0]["VehicleType"]); _RatePerDay = Convert.ToInt32(rec[0]["RatePerDay"]); //_BookingStatus = Convert.ToInt32(rec[0]["BookingStatus"]); } } public void AcceptBooking() { SqlParameter[] p = new SqlParameter[6]; p[0] = new SqlParameter("@DateBooked", SqlDbType.VarChar); p[0].Value = _DateOfBooked; p[1] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[1].Value = _VehicleId; p[2]=new SqlParameter ("@TimePeriod",SqlDbType.Int ); p[2].Value =_TimeOfPeriod ; p[3] = new SqlParameter("@AmountPaid", SqlDbType.VarChar); p[3].Value = _AmountPaid; p[4] = new SqlParameter("@BookingStatus", SqlDbType.Int); p[4].Value = _BookingStatus; p[5] = new SqlParameter("@UserId", SqlDbType.Int); p[5].Value = _UserId; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "AddBookingInfo", p); } public DataSet ShowBookingConform() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@BookingId", SqlDbType.Int); p[0].Value = _BookingId; DataSet ds = SqlHelper.ExecuteDataset (ClsConnection.GetConnection(), CommandType.StoredProcedure, "ShowBookingConform", p); return ds; } public DataSet GetBookingId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet GetBookingAmount(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet AvaliableVehicleById() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[0].Value = _VehicleId; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "AvaliableVehicleById", p); return ds; } public DataSet AvaliableVehicleByDate() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@DateOfBooked", SqlDbType.VarChar); p[0].Value = _DateOfBooked ; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "AvaliableVehicleByDate", p); return ds; } public int CancelBooking() { SqlParameter[] p = new SqlParameter[3]; p[0] = new SqlParameter("@BookingId", SqlDbType.Int); p[0].Value = _BookingId; p[1] = new SqlParameter("@DateOfBooked", SqlDbType.VarChar); p[1].Value = _DateOfBooked; p[2] = new SqlParameter("@str", SqlDbType.Int); p[2].Direction = ParameterDirection.Output; SqlHelper.ExecuteScalar(ClsConnection.GetConnection(), CommandType.StoredProcedure, "CancelBooking", p); //SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "CancelBooking", p); return (int)p[2].Value; } public DataSet DisplayCancelBooking() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@BookingId", SqlDbType.Int); p[0].Value = _BookingId; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "DisplayCancelBooking", p); return ds; } public DataSet MupleSearchDisplay() { SqlParameter[] p = new SqlParameter[2]; p[0] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[0].Value = _VehicleId; p[1] = new SqlParameter("@DateOfBooked", SqlDbType.VarChar); p[1].Value = _DateOfBooked; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "SpMultipleSearch", p); return ds; } public DataSet DiplayUserId(string stat) { DataSet ds=SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet DisplayBookingInfo(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public bool CheckAvalibility(string stat) { SqlDataReader dr = SqlHelper.ExecuteReader(ClsConnection.GetConnection(), CommandType.Text, stat); dr.Read(); if (dr.HasRows) { return true; } else { return false; } } public void UpdateBookingInfo(string stat) { SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.Text, stat); } public DataSet GetUserId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_AdminUserControl_frmEmployeeDelation : System.Web.UI.Page { ClsEmployee obj = new ClsEmployee(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int i = Convert.ToInt32(Request["EmpId"]); DataSet ds = obj.DisplyEmployee("select * from tblEmployeeInfo where EmpId=" + i); DetailsEmpView.DataSource = ds.Tables[0]; DetailsEmpView.DataBind(); } } protected void DetailsEmpView_ItemDeleting(object sender, DetailsViewDeleteEventArgs e) { string t1 = DetailsEmpView.Rows[0].Cells[1].Text; obj.EmpId = int.Parse(t1); obj.DeleteEmployee(); Response.Redirect("frmEmployeeUpdation.aspx"); } protected void DetailsEmpView_PageIndexChanging(object sender, DetailsViewPageEventArgs e) { } protected void DetailsEmpView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e) { } protected void DetailsEmpView_ItemCommand(object sender, DetailsViewCommandEventArgs e) { } protected void BtnCancel_Click(object sender, EventArgs e) { Response.Redirect("frmEmployeeUpdation.aspx?"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsPackage /// </summary> public class ClsPackage { public ClsPackage() { // // TODO: Add constructor logic here // } int _PackageId, _Price, _BookingStatus, _NoOfDays, _UserId; public int Price { get { return _Price; } set { _Price = value; } } public int PackageId { get { return _PackageId; } set { _PackageId = value; } } public int BookingStatus { get { return _BookingStatus; } set { _BookingStatus = value; } } public int NoOfDays { get { return _NoOfDays; } set { _NoOfDays = value; } } public int UserId { get { return _UserId; } set { _UserId = value; } } public string VehicleId { get { return _VehicleId; } set { _VehicleId = value; } } public string DateOfBook { get { return _DateOfBook; } set { _DateOfBook = value; } } public string Details { get { return _Details; ; } set { _Details = value; } } string _VehicleId, _DateOfBook, _Details; public DataSet GetPackageTours(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet DiplayPackageId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public DataSet DiplayVehicleaId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } public void BookPackage() { SqlParameter[] p = new SqlParameter[4]; p[0] = new SqlParameter("@PackageId", SqlDbType.Int); p[0].Value = _PackageId; p[1] = new SqlParameter("@VehicleId", SqlDbType.VarChar); p[1].Value = _VehicleId; p[2] = new SqlParameter("@UserId", SqlDbType.VarChar); p[2].Value = _UserId; p[3] = new SqlParameter("@DateOfBook", SqlDbType.VarChar); p[3].Value = _DateOfBook; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "BookPackage", p); } public void DisplayPackage() { SqlParameter[] p = new SqlParameter[1]; p[0] = new SqlParameter("@PackageId", SqlDbType.Int); p[0].Value = _PackageId; DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "DiplayAvaliabePackage", p); DataRowCollection rec = ds.Tables[0].Rows; if (rec.Count > 0) { _Details = rec[0]["Details"].ToString(); _NoOfDays = Convert.ToInt32(rec[0]["NoOfDays"]); _Price = Convert.ToInt32(rec[0]["Price"]); } } public DataSet GetPackageBookingId(string stat) { DataSet ds = SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, stat); return ds; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsLogin /// </summary> public class ClsLogin { public ClsLogin() { // // TODO: Add constructor logic here // } string _UserName, _PassWord; public string PassWord { get { return _PassWord; } set { _PassWord = value; } } public string UserName { get { return _UserName; } set { _UserName = value; } } public void InserUser() { SqlParameter []p=new SqlParameter [2]; p[0] = new SqlParameter("@username", SqlDbType.VarChar); p[0].Value = _UserName; p[1] = new SqlParameter("@password", SqlDbType.VarChar); p[1].Value = _PassWord; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Insert_EmpUsers", p); } public bool ValiDateUser() { SqlParameter[] p = new SqlParameter[2]; p[0] = new SqlParameter("@username", SqlDbType.VarChar); p[0].Value = _UserName; p[1] = new SqlParameter("@password", SqlDbType.VarChar); p[1].Value = _PassWord; SqlDataReader dr; dr= SqlHelper.ExecuteReader(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Validate_EmpUsers", p); dr.Read(); if (dr.HasRows) return true; else return false; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmBookings : System.Web.UI.Page { ClsAdminBookings obj = new ClsAdminBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.DiplayVehicleaId("select VehicleId from tblVehicle"); DdlVehicleId.Items.Clear(); DdlVehicleId.Items.Insert(0, "Select"); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { DdlVehicleId.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } } } protected void DdlVehicleId_SelectedIndexChanged(object sender, EventArgs e) { if (DdlVehicleId.SelectedItem.Text != "Select") { obj.VehicleId = DdlVehicleId.SelectedItem.Text; int i= obj.ShowBookingInfo(); if (i == 1) { TxtBookId.Text = obj.BookingId.ToString(); TxtDate.Text = obj.DateOfBooked; TxtUserId.Text = obj.UserId.ToString(); TxtTimePeriod.Text = obj.TimeOfPeriod.ToString(); TxtBookingAmount.Text = obj.BookingAmount.ToString(); TxtAmountPaid.Text = obj.AmountPaid.ToString(); TxtBookingStatus.Text = obj.BookingStatus.ToString() + " - NotAvaliable"; } if (i == 0) { TxtBookingStatus.Text = obj.BookingStatus .ToString ()+" - Vehicle Avaliable"; } } else ClearData(); } public void ClearData() { TxtAmountPaid.Text = ""; TxtBookId.Text = ""; TxtBookingAmount.Text = ""; TxtBookingStatus.Text = ""; TxtDate.Text = ""; TxtTimePeriod.Text = ""; TxtUserId.Text = ""; TxtBookId.Focus(); DdlVehicleId.SelectedIndex = 0; } protected void Button1_Click(object sender, EventArgs e) { ClearData(); } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmCustomerReports : System.Web.UI.Page { clsReports objReport = new clsReports(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { DisplayUserReport(); } } public void DisplayUserReport() { DataSet dsUser = objReport.DisplayUserReport(); if (dsUser.Tables[0].Rows.Count > 0) { GvUser.DataSource = dsUser.Tables[0]; GvUser.DataBind(); } } protected void GvUser_PageIndexChanging(object sender, GridViewPageEventArgs e) { GvUser.PageIndex = e.NewPageIndex; DisplayUserReport(); } protected void btnExcel_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GvUser .RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } protected void btnPdf_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=DocumentReport.pdf"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/pdf"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GvUser .RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmSearchVehicle : System.Web.UI.Page { clsVehicle objVehcile = new clsVehicle(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DisplayVehicleId(); } } public void DisplayVehicleId() { DataSet dsVehicle = objVehcile.GetVehicleId(); DataListVechile.DataSource = dsVehicle.Tables[0]; DataListVechile.DataBind(); } protected void DataListVechile_ItemCommand(object source, DataListCommandEventArgs e) { string vehicleId = e.CommandArgument.ToString(); objVehcile.VehicleId = vehicleId; DataSet dsVehicle = objVehcile.GetVehicleDetails(); DVVehicle.DataSource = dsVehicle.Tables[0]; DVVehicle.DataBind(); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmVehicleAdd : System.Web.UI.Page { ClsAdmin obj = new ClsAdmin(); protected void Page_Load(object sender, EventArgs e) { if (Session["Admin"] == null) { Response.Redirect("frmAdminLogin.aspx"); } if (!IsPostBack) { GetData(); } } protected void Button1_Click(object sender, EventArgs e) { TextBox t1, t2, t3, t4, t5, t6; t1 = (TextBox)GridView1.FooterRow.FindControl("TxtVehicleNO"); t2 = (TextBox)GridView1.FooterRow.FindControl("TxtDescription"); t3 = (TextBox)GridView1.FooterRow.FindControl("TxtModel"); t4 = (TextBox)GridView1.FooterRow.FindControl("TxtMake"); t5 = (TextBox)GridView1.FooterRow.FindControl("TxtVehicleType"); t6 = (TextBox)GridView1.FooterRow.FindControl("TxtRate"); obj.VehicleId = t1.Text; obj.Description = t2.Text; obj.Model = t3.Text; obj.Make = t4.Text; obj.VehicleType =Convert.ToInt16 ( t5.Text); obj.RatePerDay =Convert.ToInt16 ( t6.Text); obj.AddVehicle(); GetData(); } public void GetData() { DataSet ds = obj.DisplayVehicles("select * from tblvehicle"); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } protected void BtnHome_Click1(object sender, EventArgs e) { Response.Redirect("frmHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmBookingCancellation : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } } protected void BtnCancel_Click(object sender, EventArgs e) { obj.BookingId = Convert.ToInt32 (TxtBookingId.Text); obj.DateOfBooked = TxtDateOfBook.Text; int i= obj.CancelBooking(); Response.Redirect("frmCancelReport.aspx?id="+i.ToString ()+"&BookingId="+obj.BookingId.ToString ()); } protected void BtnHome_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for clsReports /// </summary> public class clsReports { public clsReports() { // // TODO: Add constructor logic here // } public DataSet DisplayBookingReport() { return SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.StoredProcedure, "spDisplayBookingInfo", null); } public DataSet DisplayUserReport() { string SqlStat = "select * from tblUserRegistration"; return SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, SqlStat); } public DataSet DisplayVehicleReport() { string SqlStat = "select * from tblVehicle"; return SqlHelper.ExecuteDataset(ClsConnection.GetConnection(), CommandType.Text, SqlStat); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmAdminModifyEmp : System.Web.UI.Page { ClsEmployee obj = new ClsEmployee(); protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int i = Convert.ToInt32(Request["EmpId"]); DataSet ds = obj.DisplyEmployee("select * from tblEmployeeInfo where EmpId=" + i); DetailsEmpView.DataSource = ds.Tables[0]; DetailsEmpView.DataBind(); } } protected void DetailsEmpView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e) { TextBox t2, t3, t4, t5, t6, t7, t8, t9, t10; string t1 = DetailsEmpView.Rows[0].Cells[1].Text; t2 = (TextBox)DetailsEmpView.Rows[1].Cells[1].Controls[0]; t3 = (TextBox)DetailsEmpView.Rows[2].Cells[1].Controls[0]; t4 = (TextBox)DetailsEmpView.Rows[3].Cells[1].Controls[0]; t5 = (TextBox)DetailsEmpView.Rows[4].Cells[1].Controls[0]; t6 = (TextBox)DetailsEmpView.Rows[5].Cells[1].Controls[0]; t7 = (TextBox)DetailsEmpView.Rows[6].Cells[1].Controls[0]; t8 = (TextBox)DetailsEmpView.Rows[7].Cells[1].Controls[0]; t9 = (TextBox)DetailsEmpView.Rows[8].Cells[1].Controls[0]; t10 = (TextBox)DetailsEmpView.Rows[9].Cells[1].Controls[0]; obj.EmpId = int.Parse(t1); obj.EmpName = t2.Text; obj.Surname = t3.Text; obj.Address = t4.Text; obj.City = t5.Text; obj.State = t6.Text; obj.ZipCode = Convert.ToInt32(t7.Text); obj.WorkOnVehicle = Convert.ToInt32(t8.Text); obj.Salary = Convert.ToInt32(t9.Text); obj.JobDesc = t10.Text; obj.UpdateEmployee(); Response.Redirect("frmEmployeeUpdation.aspx"); } protected void DetailsEmpView_ItemCommand(object sender, DetailsViewCommandEventArgs e) { //Response.Redirect("frmEmployeeUpdation.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Admin_frmEmployeeRegistration : System.Web.UI.Page { ClsEmployee obj = new ClsEmployee(); protected void Page_Load(object sender, EventArgs e) { } protected void BtnRegister_Click(object sender, EventArgs e) { obj.EmpName = TxtName.Text; obj.Surname = TxtSurName.Text; obj.Address = TxtAddress.Text; obj.City = DdlCity.SelectedItem.ToString(); obj.State = DdlState.SelectedItem.ToString(); obj.ZipCode = Convert.ToInt32(TxtZipCode.Text); obj.WorkOnVehicle = int.Parse(TxtWorkOnVehicle.Text); obj.Salary = Convert.ToInt16(TxtSalary.Text); obj.JobDesc = TxtJobDesc.Text; obj.InsertEmployee(); ClsLogin log = new ClsLogin(); log.UserName = TxtName.Text; log.PassWord = Txt<PASSWORD>.Text; log.InserUser(); LblMessage.Visible = true; LblMessage.Text = "Employee Successfully Registered..."; Page.RegisterClientScriptBlock("Dhanush","<script>alert('Registered Successfully..')</script>"); GetData(); } protected void BtnCancel_Click(object sender, EventArgs e) { GetData(); } protected void LinkLogin_Click(object sender, EventArgs e) { Response.Redirect("frmAdminLogin.aspx"); } public void GetData() { TxtName.Text = ""; TxtSurName.Text = ""; TxtSalary.Text = ""; TxtWorkOnVehicle.Text = ""; TxtAddress.Text = ""; TxtZipCode.Text = ""; DdlState.SelectedIndex = 0; DdlCity.SelectedIndex = 0; TxtName.Focus(); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmPackages : System.Web.UI.Page { ClsPackage obj = new ClsPackage(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { DataSet ds = obj.GetPackageTours("select * from tblPakageInfo"); GridPackage.DataSource = ds.Tables[0]; GridPackage.DataBind(); } } protected void BtnPackage_Click(object sender, EventArgs e) { Response.Redirect("frmPackageBook.aspx"); } protected void BtnCancel_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmLogin : System.Web.UI.Page { ClsCustomerLogin obj = new ClsCustomerLogin(); bool found; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { TxtUserName.Focus(); } } protected void BtnLogin_Click(object sender, EventArgs e) { if (TxtUserName.Text != "" && TxtPassWord.Text != "") { obj.UserName = TxtUserName.Text; obj.PassWord = <PASSWORD>; found = obj.ValiDateUser(); if (found == true) { Session["User"] = obj.UserName; Response.Redirect("~/CustomerSection/frmUserHome.aspx"); } else { LblMessage.Visible = true; LblMessage.Text = "Invalid UserName TryAgain..."; } } else { LblMessage.Visible = true; LblMessage.Text = "Must Enter UserName and PassWord"; } } protected void BtnCancel_Click(object sender, EventArgs e) { TxtUserName.Text = ""; TxtPassWord.Text = ""; TxtUserName.Focus(); } protected void LnkNewUser_Click(object sender, EventArgs e) { Response.Redirect("CustomerSection//frmRegistration.aspx"); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for ClsConnection /// </summary> public static class ClsConnection { public static string GetConnection() { return ConfigurationManager.ConnectionStrings["Cnstsr"].ConnectionString; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmUserHome : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } LblMessage.Text ="<h2> Welcome To : "+ Session["User"].ToString()+"</h2>"; } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmBookingUpdation : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { // DataSet ds = obj.GetBookingId("select BookingId from tblBookingInfo "); // DataSet ds1 = obj.GetUserId("select UserId from tblUserRegistration where UserName='" + Session["User"].ToString() + "'"); DataSet ds = obj.GetBookingId("select BookingId from tblBookingInfo where UserId In (select UserId from tblUserRegistration where UserName='" + Session["User"].ToString() + "')"); // DataSet ds = obj.GetBookingId("select BookingId from tblBookingInfo where UserId=(); DdlBookingId.Items.Clear(); DdlBookingId.Items.Insert(0, "Select"); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { DdlBookingId.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } } } protected void DdlPackageId_SelectedIndexChanged(object sender, EventArgs e) { if (DdlBookingId.SelectedItem.Text != null) { DataSet ds = obj.DisplayBookingInfo("select DateOfBooked,VehicleId,UserId from tblBookingInfo where BookingId=" + DdlBookingId.SelectedItem.Text); TxtBookingDate.Text = ds.Tables[0].Rows[0][0].ToString(); TxtVehicleId.Text = ds.Tables[0].Rows[0][1].ToString(); TxtUserName.Text = Session ["User"].ToString(); TxtUseID.Text = ds.Tables[0].Rows[0][2].ToString(); } else { LblMessage.Text = "Select Your TransId"; } } protected void BtnBooking_Click(object sender, EventArgs e) { obj.UpdateBookingInfo("update tblBookingInfo set DateOfBooked='" + TxtRequiredDate.Text + "' where BookingId=" + DdlBookingId.SelectedItem.Text); Response.Redirect ("frmConfirmation.aspx?BookingId="+DdlBookingId.SelectedItem.Text.ToString ()+"&Date='"+TxtRequiredDate.Text +"'" ); } protected void BtnCancel_Click(object sender, EventArgs e) { TxtBookingDate.Text = ""; TxtUseID.Text = ""; TxtUserName.Text =""; TxtVehicleId.Text =""; TxtRequiredDate.Text = ""; DdlBookingId.SelectedIndex = 0; } protected void BtnBack_Click(object sender, EventArgs e) { Response.Redirect("frmUserHome.aspx"); } protected void BtnAvaliability_Click(object sender, EventArgs e) { bool CheckAvaliblity; CheckAvaliblity = obj.CheckAvalibility("select * from tblBookingInfo where VehicleId='" + TxtVehicleId.Text + "' and DateOfBooked='" + TxtRequiredDate.Text + "'"); if (CheckAvaliblity == true) { LblMessage.Visible = true; LblMessage.Text = " Vehicle Not Avliable "; } else { LblMessage.Visible = true; LblMessage.Text = " Vehicle Avliable "; } } } <file_sep>using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CompNetwork.DAL; /// <summary> /// Summary description for ClsUserRegistration /// </summary> public class ClsUserRegistration { public ClsUserRegistration() { // // TODO: Add constructor logic here // } int _UserId; public int UserId { get { return _UserId; } set { _UserId = value; } } string _UserName, _Surname, _EmailId, _Address, _City, _State, _PassWord; public string City { get { return _City; } set { _City = value; } } public string State { get { return _State; } set { _State = value; } } public string PassWord { get { return _PassWord; } set { _PassWord = value; } } public string Address { get { return _Address; } set { _Address = value; } } public string EmailId { get { return _EmailId; } set { _EmailId = value; } } public string Surname { get { return _Surname; } set { _Surname = value; } } public string UserName { get { return _UserName; } set { _UserName = value; } } string _MobileNo, _ZipCode; public string MobileNo { get { return _MobileNo; } set { _MobileNo = value; } } public string ZipCode { get { return _ZipCode; } set { _ZipCode = value; } } public void InsertUserRegistration() { SqlParameter[] p = new SqlParameter[8]; p[0] = new SqlParameter("@UserName", SqlDbType.VarChar); p[0].Value = _UserName; p[1] = new SqlParameter("@Surname", SqlDbType.VarChar); p[1].Value = _Surname ; p[2] = new SqlParameter("@EmailId", SqlDbType.VarChar); p[2].Value = _EmailId ; p[3] = new SqlParameter("@MobileNo", SqlDbType.VarChar); p[3].Value = _MobileNo ; p[4] = new SqlParameter("@Address", SqlDbType.VarChar); p[4].Value = _Address ; p[5] = new SqlParameter("@City", SqlDbType.VarChar); p[5].Value = _City ; p[6] = new SqlParameter("@State", SqlDbType.VarChar); p[6].Value = _State ; p[7] = new SqlParameter("@ZipCode", SqlDbType.VarChar); p[7].Value = _ZipCode; SqlHelper.ExecuteNonQuery(ClsConnection.GetConnection(), CommandType.StoredProcedure, "Insert_userRegistraion", p); } } <file_sep>using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class CustomerSection_frmBookingDisplay : System.Web.UI.Page { ClsUserBookings obj = new ClsUserBookings(); protected void Page_Load(object sender, EventArgs e) { if (Session["User"] == null) { Response.Redirect("frmLogin.aspx"); } if (!IsPostBack) { if (Request["Text"] != null) { LblPaid.Visible = true; LblPaid.Text = Request["Text"].ToString(); LblPaid.Visible = true; } if (Request["Text2"] != null) { LblPaid.Text = Request["Text2"].ToString(); LblPaid.Visible = true; } obj.BookingId = Convert.ToInt32(Request["BookingId"]); DataSet ds = obj.ShowBookingConform(); LblMessage.Visible = true; LblMessage.Text = "For Amount Paying Click On Amount! "; GridViewDisplay.DataSource = ds.Tables[0]; GridViewDisplay.DataBind(); } } public int DisplayUserId() { string UserName = Session["User"].ToString(); DataSet ds = obj.DiplayUserId("select UserId from tblUserRegistration where UserName='" + UserName + "'"); int i = Convert.ToInt32(ds.Tables[0].Rows[0][0]); return i; } public string DisplayUserName() { string UserName = Session["User"].ToString(); return UserName; } protected void BtnCancel_Click(object sender, EventArgs e) { Response.Redirect("frmVehicleBooking.aspx"); } protected void BtnAmountPay_Click(object sender, EventArgs e) { DataSet ds = obj.GetBookingId("Select Max(BookingId) from tblBookingInfo"); Response.Redirect("frmAmountPaid.aspx?BookingId=" + ds.Tables[0].Rows[0][0].ToString() + "&Text2=AmountPaid"); } }
843bf0e13a7eb6988e1bada2bab0fc17c325147b
[ "C#" ]
38
C#
Shekhar938/VHP-Vehicle-Hiring-System
d754455f4295c50322808ddede1dfc21481dd068
4798f4cf26c2bd70964c967450ae300eb78fbb8a
refs/heads/main
<repo_name>NishantJawla/Perkant-Tech-Task<file_sep>/index.js const express = require("express"); const app = express(); const secret = require("./utility/secret"); const mongoose = require("mongoose"); const userRouters = require("./routes/user"); var cors = require('cors') const path = require('path'); require('dotenv').config() //middlewares app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cors()) app.use("/api", userRouters); //connection to mongo db mongoose .connect(secret.MONGOURL, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, }) .then(() => { console.log("Database is connected"); }) .catch((err) => { console.log(err); }); if(process.env.NODE_ENV === 'production'){ app.use(express.static(path.join(__dirname, '/client/build'))) app.get('*',(req,res) => { res.sendFile(path.join(__dirname,'client','build','index.html')) }) } else { app.get('/',(req,res) =>{ res.send("api running") }) app.get('/homepage',(req,res) =>{ res.send("api running") }) app.get('/godmode',(req,res) =>{ res.send("api running") }) } // listening to server let PORT = secret.PORT || 7000 app.listen(PORT, () => { console.log("listening on 7000"); }); <file_sep>/client/src/pages/homepage/homepage.component.jsx import {useState} from 'react' import { LockClosedIcon } from '@heroicons/react/solid' import {signin,authenticate,isAuthenticated} from "./homepage.api-calls" import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import {Redirect} from "react-router-dom" const axios = require("axios"); const HomePage= () => { const [values, setValues] = useState({ name: "", password: "", error: "", didRedirect: false, }); const [user, setUser] = useState({ user: undefined }); const {name,password,error} = values; const handleChange = (name) => (event) => { setValues({ ...values, error: false, [name]: event.target.value }); }; const onSubmit = (event) => { event.preventDefault(); setValues({ ...values, error: false, loading: true }); signin({ name, "plainPassword" : <PASSWORD> }) .then((data) => { if (data.error) { errorMessage() setValues({ ...values, error: data.error, loading: false }); } else { authenticate(data, () => { setValues({ ...values, didRedirect: true, }); }); } }) .catch( (err) => { errorMessage() // console.log(err); // console.log("signin request failed") }); }; const errorMessage = () => { if(error){ toast.error(error, { position: 'top-right', autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); } }; const getDataFromServer = async (token) => { try { const response = await axios .get("http://localhost:7000/api/getuser",{ headers: {"Authorization" : `${token}`} }); setUser({...user, user: response.data}) } catch (e) { // console.log(e) } } if(isAuthenticated()) { if(user.user){ if(user.user.role === 1){ return (<Redirect to="/scoreboard" />); } else { return(<h1>You are not Admin!!!</h1>) } } } const {token} = isAuthenticated(); getDataFromServer(token); return ( <div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8"> <ToastContainer /> <div className="max-w-md w-full space-y-8"> <div> <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">Sign in to ScoreBoard</h2> </div> <form className="mt-8 space-y-6"> <input type="hidden" name="remember" defaultValue="true" /> <div className="rounded-md shadow-sm -space-y-px"> <div> <label htmlFor="email-address" className="sr-only"> Email address </label> <input id="name" name="name" type="text" value={name} autoComplete="name" required className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="Name" onChange={handleChange("name")} /> </div> <div> <label htmlFor="password" className="sr-only"> Password </label> <input id="password" name="password" type="password" autoComplete="current-password" required value={password} className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 focus:z-10 sm:text-sm" placeholder="<PASSWORD>" onChange={handleChange("password")} /> </div> </div> <div> <button className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" onClick={onSubmit} > <span className="absolute left-0 inset-y-0 flex items-center pl-3"> <LockClosedIcon className="h-5 w-5 text-indigo-500 group-hover:text-indigo-400" aria-hidden="true" /> </span> Sign in </button> </div> </form> </div> </div> ) } export default HomePage<file_sep>/client/src/redux/score-reducer/score.action.js import {ScoreActionTypes} from './score.action-types' export const setScore = (score) => ( { type: ScoreActionTypes.SET_SCORE_DATA, payload: score } )<file_sep>/README.md # Perkant-Tech-Task<file_sep>/routes/user.js const express = require("express"); const router = express.Router(); const { check, validationResult } = require("express-validator"); const passport = require("passport"); require("../utility/passport")(passport); const { signupHandler, loginHandler, getUserHandler, } = require("../controller/user"); //Private Route to create a new admin //Post Request // api/signup router.post( "/signup", [ check("name") .notEmpty() .withMessage("Name Field is Required") .isLength({ min: 4 }) .withMessage("Name should be at least 3 char") .matches(/^[a-zA-Z_ ]*$/, "i") .withMessage("Name Field is inValid"), check("plainPassword") .isLength({ min: 5 }) .withMessage("Password should be at least 5 <PASSWORD>") .notEmpty() .withMessage("Password Field is Required"), ], passport.authenticate("jwt", { session: false }), signupHandler ); //Public Route to login //Post Request // api/signin router.post( "/signin", [ check("name").notEmpty().withMessage("Name Field is Required"), check("plainPassword", "<PASSWORD>") .isLength({ min: 5 }) .notEmpty() .withMessage("Password Field is Required"), ], loginHandler ); //Private Route to get user data //get Request // api/getuser router.get( "/getuser", passport.authenticate("jwt", { session: false }), getUserHandler ); module.exports = router; <file_sep>/client/src/.env.example REACT_APP_ENVIRONMENT = DEV REACT_APP_FIREBASE_KEY = REACT_APP_FIREBASE_DOMAIN = REACT_APP_FIREBASE_DATABASE = REACT_APP_FIREBASE_PROJECT_ID = REACT_APP_FIREBASE_STORAGE_BUCKET = REACT_APP_FIREBASE_SENDER_ID = REACT_APP_MESSAGING_APP_ID = REACT_APP_MEASURMENT_ID = <file_sep>/client/src/redux/root.reducer.js import {combineReducers} from "redux"; import userReducer from "./user-reducer/user.reducer"; import scoreReducer from "./score-reducer/score.reducer"; export default combineReducers({ user: userReducer, score: scoreReducer })<file_sep>/client/src/redux/score-reducer/score.action-types.js export const ScoreActionTypes = { 'SET_SCORE_DATA' : 'SET_SCORE_DATA', } <file_sep>/controller/user.js const bcrypt = require("bcryptjs"); const { validationResult } = require("express-validator"); const saltRounds = 10; const jwt = require("jsonwebtoken"); const secret = require("../utility/secret"); const User = require("../models/user"); const statusCodes = require("../utility/statuscodes") exports.signupHandler = (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(statusCodes.BAD_REQUEST).json({ status: statusCodes.BAD_REQUEST, error: errors.array()[0].msg, }); } User.findOne({ name: req.body.name }).exec((err, user) => { if (user) { return res.status(statusCodes.BAD_REQUEST).json({ status: statusCodes.BAD_REQUEST, error: "User with this name already exist!", }); } bcrypt.hash(req.body.plainPassword, saltRounds, (err, hash) => { const user = new User(req.body); user.encryptedPassword = <PASSWORD>; user.save((err, user) => { if (err || !user) { console.log(err); return res.status(statusCodes.BAD_REQUEST).json({ status: statusCodes.BAD_REQUEST, error: "Failed to save user", }); } res.status(statusCodes.OK).json({ status: statusCodes.OK, msg: "User Created Succesfully", }); }); }); }); }; exports.loginHandler = (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(statusCodes.BAD_REQUEST).json({ status: statusCodes.BAD_REQUEST, msg: errors.array()[0].msg, error: errors.array()[0].msg, }); } User.findOne({ name: req.body.name }).exec((err, user) => { if (err || !user) { if (err) { console.log("some error occured"); } return res.status(statusCodes.BAD_REQUEST).json({ error: "User with this name does not exist", }); } if (user) { bcrypt.compare( req.body.plainPassword, user.encryptedPassword, function (err, result) { if (result != true) { return res.status(statusCodes.BAD_REQUEST).json({ error: "Please Enter correct Password", }); } else { const payload = { id: user.id, name: user.name, }; jwt.sign( payload, secret.SECRET, { expiresIn: "30m" }, (err, token) => { return res.status(statusCodes.OK).json({ token: "Bearer " + token, msg: "User succesfully loggedin!", }); } ); } } ); } }); }; exports.getUserHandler = (req, res) => { res.status(statusCodes.OK).json({ msg: "Succesfully Loaded Data", name: req.user.name, role: req.user.role, }); }; <file_sep>/client/src/routes.js import React from "react"; import { BrowserRouter, Switch, Route } from "react-router-dom"; import { Provider } from "react-redux"; import store from "./redux/store"; import HomePage from "./pages/homepage/homepage.component"; import Scoreboard from "./pages/scoreboard/scoreboard.component"; const Routes = () => { return ( <Provider store={store}> <BrowserRouter> <Switch> <Route path="/" exact component={HomePage} /> <Route path="/scoreboard" exact component={Scoreboard} /> </Switch> </BrowserRouter> </Provider> ); }; export default Routes;<file_sep>/utility/secret.js require('dotenv').config() const secret = { PORT : process.env.PORT, MONGOURL : process.env.MONGOURL, SECRET : process.env.SECRET } module.exports = secret;
a28a35efe05dcb241b718885268c574da645f759
[ "JavaScript", "Markdown", "Shell" ]
11
JavaScript
NishantJawla/Perkant-Tech-Task
eda92b27f28a11f18b10b63143e0fddf23fff57f
45d7f4ead253742e109171a6bdd502cf2cc1ec53
refs/heads/master
<file_sep>Herman [a SassDoc theme] ======================== ``` npm install sassdoc-theme-herman ``` At [OddBird][oddbird], we wanted to a tool to help us document the entire front end of a project, from brand guidelines to UX Elements and code patterns. Herman is our odd [SassDoc][SassDoc] theme, still in alpha-development, with a number of extra features for documenting user-experience and code patterns: - Font specimens - Color palettes - SVG icon previews - Referencing & rendering Jinja/Nunjucks macros from the Sass docs - more on the way! [oddbird]: http://oddbird.net/ [SassDoc]: http://sassdoc.com/ <file_sep>'use strict'; var parse = require('../lib/parse.js'); var assert = require('assert'); describe('parse', function () { describe('sassJson', function () { it('parses sassJson', function () { var contents = '/*! json-encode: {"a": 1} */'; var expected = { a: 1 }; assert.deepEqual(parse.sassJson(contents), expected); }); it('parses sassJson with cruft after it', function () { var contents = '/*! json-encode: {"a": 1} */\n\n' + '/*# sourceMappingURL=sass_json.bundle.css.map*/'; var expected = { a: 1 }; assert.deepEqual(parse.sassJson(contents), expected); }); }); }); <file_sep>'use strict'; var assert = require('assert'); var path = require('path'); var sinon = require('sinon'); var theme = require('../'); describe('macro annotation', function () { before(function () { this.env = { templatepath: path.resolve(__dirname, 'templates') }; this.macro = theme.annotations[0](this.env); }); describe('parse', function () { it('splits on colon', function () { assert.deepEqual( this.macro.parse('foo.j2:name'), { file: 'foo.j2', name: 'name' } ); }); }); describe('resolve', function () { it('warns and exits if no templatepath and @macro used', function () { var env = { logger: { warn: sinon.stub() }}; var macro = theme.annotations[0](env); var data = [{ macro: {}}]; macro.resolve(data); assert.deepEqual(data, [{ macro: {}}]); assert( env.logger.warn.calledWith( 'Must pass in a templatepath if using @macro.')); }); it('warns only once about missing templatepath', function () { var env = { logger: { warn: sinon.stub() }}; var macro = theme.annotations[0](env); var data = [{ macro: {}}, { macro: {}}]; macro.resolve(data); sinon.assert.calledOnce(env.logger.warn); }); it('does not warn on lack of templatepath if @macro not used', function () { var env = { logger: { warn: sinon.stub() }}; var macro = theme.annotations[0](env); var data = [{}]; macro.resolve(data); assert.deepEqual(data, [{}]); sinon.assert.notCalled(env.logger.warn); }); it('renders macro and doc', function () { var data = [{ macro: { file: 'macros.j2', name: 'mymacro' }}]; this.macro.resolve(data); assert.deepEqual(data, [{ macro: { file: 'macros.j2', name: 'mymacro', args: '"one","two"', doc: 'This is my macro.', rendered: 'one then two.' } }]); }); }); }); describe('icons annotation', function () { before(function () { this.env = { templatepath: path.resolve(__dirname, 'templates') }; this.icons = theme.annotations[1](this.env); }); describe('parse', function () { it('splits on space and colon', function () { assert.deepEqual( this.icons.parse('icons/ foo.j2:name'), { iconsPath: 'icons/', macroFile: 'foo.j2', macroName: 'name' } ); }); }); describe('resolve', function () { it('warns and exits if no templatepath and @icons used', function () { var env = { logger: { warn: sinon.stub() }}; var icons = theme.annotations[1](env); var data = [{ icons: {}}]; icons.resolve(data); assert.deepEqual(data, [{ icons: {}}]); assert( env.logger.warn.calledWith( 'Must pass in a templatepath if using @icons.')); }); it('warns only once about missing templatepath', function () { var env = { logger: { warn: sinon.stub() }}; var icons = theme.annotations[1](env); var data = [{ icons: {}}, { icons: {}}]; icons.resolve(data); sinon.assert.calledOnce(env.logger.warn); }); it('does not warn on lack of templatepath if @icons not used', function () { var env = { logger: { warn: sinon.stub() }}; var icons = theme.annotations[1](env); var data = [{}]; icons.resolve(data); assert.deepEqual(data, [{}]); sinon.assert.notCalled(env.logger.warn); }); it('renders icons', function () { var data = [{ icons: { iconsPath: 'icons/', macroFile: 'macros.j2', macroName: 'icon' }}]; this.icons.resolve(data); assert.deepEqual(data, [{ icons: [ { name: 'ok', path: 'icons/ok.svg', rendered: 'rendered ok' }, { name: 'warning', path: 'icons/warning.svg', rendered: 'rendered warning' } ] }]); }); }); }); describe('preview annotation', function () { before(function () { this.preview = theme.annotations[2](); }); describe('parse', function () { it('splits on comma and strips whitespace', function () { assert.deepEqual( this.preview.parse(' foo,bar, baz'), [ 'foo', 'bar', 'baz' ] ); }); }); }); <file_sep>'use strict'; var Promise = require('bluebird'); var vfs = require('vinyl-fs'); module.exports = function (src, dest) { return new Promise(function (resolve, reject) { vfs.src(src) .pipe(vfs.dest(dest)) .on('error', reject) .on('finish', resolve); }); }; <file_sep>'use strict'; var minify = require('html-minifier').minify; var path = require('path'); var Promise = require('bluebird'); var rename = require('gulp-rename'); var through = require('through2'); var vfs = require('vinyl-fs'); // Asynchronously render the template ``tpl`` to the file ``dest`` using // Nunjucks env ``env`` and context ``ctx``. module.exports = function (env, tpl, dest, ctx) { var parsedDest = path.parse(dest); var renderStr = Promise.promisify(env.renderString, { context: env }); var transform = function (file, enc, cb) { if (!file.isBuffer()) { return cb(); } return renderStr(file.contents.toString(enc), ctx) .then(function (html) { return minify(html, { collapseWhitespace: true }); }) .then(function (html) { file.contents = new Buffer(html); cb(null, file); }) .catch(function (err) { cb(err); }); }; var stream = through.obj(transform); return new Promise(function (resolve, reject) { vfs.src(tpl) .pipe(stream) .pipe(rename(parsedDest.base)) .pipe(vfs.dest(parsedDest.dir)) .on('error', reject) .on('finish', resolve); }); };
1fd7c91b9447e3db5418190101205f71c75a92bc
[ "Markdown", "JavaScript" ]
5
Markdown
sshyran/sassdoc-theme-herman
d4a5dae7db1841bb5021002e5c067ffbb7c4a7bd
61b441e69378718c0f6f3d01df77c0ba8f2260e7
refs/heads/master
<file_sep>#ifndef ODOM_LISTENER_INCLUDE #define ODOM_LISTENER_INCLUDE #include <string> #include <ros/ros.h> #include <nav_msgs/Odometry.h> namespace swarm_navigator { class Position { private: double x_,y_,z_; public: Position(){}; void setX(double x); void setY(double y); void setZ(double z); double getX(); double getY(); double getZ(); void update(double x,double y,double z); }; class Orientation { private: double x_,y_,z_,w_; public: Orientation(){}; void setX(double x); void setY(double y); void setZ(double z); void setW(double w); double getX(); double getY(); double getZ(); double getW(); void update(double x,double y,double z,double w); }; class OdomListener{ private: ros::NodeHandle nh_; ros::Subscriber subscriber; std::string topic_; int seq_; Position position_; Orientation orientation_; double linear_velocity_; double angular_velocity_; void update(const nav_msgs::Odometry::ConstPtr& msg); public: OdomListener(ros::NodeHandle &nh,std::string topic); int getSeq(); Position getPosition(); Orientation getOrientation(); double getLinerVelocity(); double getAngularVelocity(); void start(); }; } #endif // ROS_INFO("Seq: [%d]", msg->header.seq); // ROS_INFO("Position-> x: [%f], y: [%f], z: [%f]", msg->pose.pose.position.x,msg->pose.pose.position.y, msg->pose.pose.position.z); // ROS_INFO("Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]", msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w); // ROS_INFO("Vel-> Linear: [%f], Angular: [%f]", msg->twist.twist.linear.x,msg->twist.twist.angular.z); // }<file_sep>#include <message_filters/subscriber.h> #include <message_filters/time_synchronizer.h> #include <sensor_msgs/PointCloud2.h> #include <nav_msgs/Odometry.h> #include <geometry_msgs/PoseStamped.h> #include <ros/ros.h> #include <swarm_navigator/cmd_val_controller.h> #include <swarm_navigator/odom_listener.h> #include <swarm_navigator/point_cloud_listener.h> using namespace sensor_msgs; using namespace message_filters; swarm_navigator::CmdValController* controller; // void callback(const nav_msgs::Odometry::ConstPtr& odom, const sensor_msgs::PointCloud2ConstPtr& points) // { // // if(odom==NULL) // // ROS_INFO("pointcloud recieved______________________"); // // else // // ROS_INFO("odom recieved ######################"); // ROS_INFO("ODOM Seq: [%d]", odom->header.seq); // ROS_INFO("POINT Seq: [%d]", points->header.seq); // } void callback(const geometry_msgs::PoseStamped& goal) { // if(odom==NULL) // ROS_INFO("pointcloud recieved______________________"); // else // ROS_INFO("odom recieved ######################"); ROS_INFO("Came...."); // ROS_INFO("POINT Seq: [%d]", points->header.seq); controller->achieveGoal(goal); } int main(int argc, char** argv) { ros::init(argc, argv, "navigation"); ros::NodeHandle nh; std::string topic_cmd_val; std::string topic_odom; std::string base_link; std::string odom_link; ros::NodeHandle private_nh("~"); private_nh.param("cmd_vel_topic", topic_cmd_val, std::string("/mobile_base/commands/velocity")); private_nh.param("odom_topic", topic_odom, std::string("/odom")); private_nh.param("base_link", base_link, std::string("base_footprint")); private_nh.param("odom_link", odom_link, std::string("odom")); controller = new swarm_navigator::CmdValController(nh,topic_cmd_val,base_link,odom_link); // message_filters::Subscriber<nav_msgs::Odometry> odom_sub(nh, "/odom", 1); // message_filters::Subscriber<sensor_msgs::PointCloud2> points_sub(nh, "/depth_camera/depth_camera/depth/points", 1); // TimeSynchronizer<nav_msgs::Odometry, sensor_msgs::PointCloud2> sync(odom_sub, points_sub, 10); // sync.registerCallback(boost::bind(&callback, _1, _2)); ros::NodeHandle simple_nh("move_base_simple"); ros::Subscriber goal_sub_ = simple_nh.subscribe("goal", 1, callback); // ros::Subscriber goal_sub_ = simple_nh.subscribe<geometry_msgs::PoseStamped>("goal", 1); ros::spin(); return 0; }<file_sep>#include <iostream> #include <swarm_navigator/cmd_val_controller.h> #include <swarm_navigator/odom_listener.h> #include <swarm_navigator/point_cloud_listener.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> namespace swarm_navigator { class Navigator{ private: ros::NodeHandle nh_; float liner_velocity; float angular_velocity; public: Navigator(ros::NodeHandle &nh){ nh_ = nh; liner_velocity = 0.25; angular_velocity = 0.75; } void executeContoller(std::string topic){ CmdValController* controller = new CmdValController(nh_,topic); // controller.driveKeyboard(); double d; char cmd[50]; while(controller->ready()){ std::cin.getline(cmd, 50); // if(cmd[0]!='w' && cmd[0]!='a' && cmd[0]!='d' && cmd[0]!='s' && cmd[0]!='q') // { // std::cout << "invalid command:" << cmd << "\n"; // continue; // } if(cmd[0]=='w'){ controller->foward(); } //turn left else if(cmd[0]=='a'){ controller->left(); } //turn right else if(cmd[0]=='d'){ controller->right(); } //turn back else if(cmd[0]=='s'){ controller->backward(); } //turn stop else if(cmd[0]=='x'){ controller->stop(); } else if(cmd[0]=='g'){ std::cin >> d; controller->driveForward(d); } else if(cmd[0]=='l'){ std::cin >> d; controller->turn(false,d); } else if(cmd[0]=='r'){ std::cin >> d; controller->turn(true,d); } //quit else if(cmd[0]=='q'){ break; } } } void executeOdomListener(std::string topic){ OdomListener* o_listener = new OdomListener(nh_,topic); o_listener->start(); } void executePointCloudListener(std::string topic){ PointCloudListener* p_listener = new PointCloudListener(nh_,topic); p_listener->start(); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "navigator"); ros::NodeHandle nh; std::string topic_cmd_val; std::string topic_odom; std::string topic_point_cloud; ros::NodeHandle private_nh("~"); private_nh.param("cmd_vel_topic", topic_cmd_val, std::string("/cmd_vel")); private_nh.param("odom_topic", topic_odom, std::string("/odom")); private_nh.param("point_cloud_topic", topic_point_cloud, std::string("/depth_camera/depth_camera/depth/points")); swarm_navigator::Navigator* navigator = new swarm_navigator::Navigator(nh); navigator->executeContoller(topic_cmd_val); // navigator->executePointCloudListener(topic_point_cloud); // navigator->executeOdomListener(topic_odom); } // #include <message_filters/subscriber.h> // #include <message_filters/time_synchronizer.h> // #include <sensor_msgs/PointCloud2.h> // #include <nav_msgs/Odometry.h> // using namespace sensor_msgs; // using namespace message_filters; // void callback(const nav_msgs::Odometry::ConstPtr& odom, const sensor_msgs::PointCloud2ConstPtr& points) // { // // if(odom==NULL) // // ROS_INFO("pointcloud recieved______________________"); // // else // // ROS_INFO("odom recieved ######################"); // ROS_INFO("ODOM Seq: [%d]", odom->header.seq); // ROS_INFO("POINT Seq: [%d]", points->header.seq); // } // int main(int argc, char** argv) // { // ros::init(argc, argv, "navigation"); // ros::NodeHandle nh; // message_filters::Subscriber<nav_msgs::Odometry> odom_sub(nh, "/odom", 1); // message_filters::Subscriber<sensor_msgs::PointCloud2> points_sub(nh, "/depth_camera/depth_camera/depth/points", 1); // TimeSynchronizer<nav_msgs::Odometry, sensor_msgs::PointCloud2> sync(odom_sub, points_sub, 10); // sync.registerCallback(boost::bind(&callback, _1, _2)); // ros::spin(); // return 0; // }<file_sep>#ifndef POINT_CLOUD_LISTENER_INCLUDE #define POINT_CLOUD_LISTENER_INCLUDE #include <string> #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> namespace swarm_navigator { class PointCloudListener{ private: ros::NodeHandle nh_; ros::Subscriber subscriber; std::string topic_; void update(const sensor_msgs::PointCloud2ConstPtr& msg); public: PointCloudListener(ros::NodeHandle &nh,std::string topic); void start(); }; } #endif <file_sep>#include <swarm_navigator/odom_listener.h> #include "ros/ros.h" #include "nav_msgs/Odometry.h" namespace swarm_navigator { /* OdomListener implementations */ OdomListener::OdomListener(ros::NodeHandle &nh,std::string topic){ nh_ = nh; topic_ = topic; seq_ = 0; position_ = Position(); orientation_ = Orientation(); linear_velocity_ = 0.0; angular_velocity_ = 0.0; } Position OdomListener::getPosition(){ return position_; } Orientation OdomListener::getOrientation(){ return orientation_; } double OdomListener::getLinerVelocity(){ return linear_velocity_; } double OdomListener::getAngularVelocity(){ return angular_velocity_; } void OdomListener::start(){ // subscriber = nh_.subscribe(topic_, 1000, update); subscriber = nh_.subscribe(topic_, 1000, &OdomListener::update, this); ros::spin(); } void OdomListener::update(const nav_msgs::Odometry::ConstPtr& msg){ // seq_ = msg->header.seq; // position_.update( msg->pose.pose.position.x,msg->pose.pose.position.y, msg->pose.pose.position.z); // orientation_.update(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w); // linear_velocity_ = msg->twist.twist.linear.x; // angular_velocity_ = msg->twist.twist.angular.z; // ROS_INFO("Seq: [%d]", seq_); // ROS_INFO("Position-> x: [%f], y: [%f], z: [%f]", position_.getX(),position_.getY(), position_.getZ()); // ROS_INFO("Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]",orientation_.getX(), orientation_.getY(), orientation_.getZ(), orientation_.getW()); // ROS_INFO("Vel-> Linear: [%f], Angular: [%f]", linear_velocity_,angular_velocity_); ROS_INFO("odom recieved ######################"); } /* Position implementations */ void Position::setX(double x){ x_ = x; } void Position::setY(double y){ y_ = y; } void Position::setZ(double z){ z_ = z; } double Position::getX(){ return x_; } double Position::getY(){ return y_; } double Position::getZ(){ return z_; } void Position::update(double x,double y,double z){ x_ = x; y_ = y; z_ = z; } /* Orientation implementations */ void Orientation::setX(double x){ x_ = x; } void Orientation::setY(double y){ y_ = y; } void Orientation::setZ(double z){ z_ = z; } void Orientation::setW(double w){ w_ = w; } double Orientation::getX(){ return x_; } double Orientation::getY(){ return y_; } double Orientation::getZ(){ return z_; } double Orientation::getW(){ return w_; } void Orientation::update(double x,double y,double z,double w){ x_ = x; y_ = y; z_ = z; w_ = w; } } // void chatterCallback(const nav_msgs::Odometry::ConstPtr& msg) // { // ROS_INFO("Seq: [%d]", msg->header.seq); // ROS_INFO("Position-> x: [%f], y: [%f], z: [%f]", msg->pose.pose.position.x,msg->pose.pose.position.y, msg->pose.pose.position.z); // ROS_INFO("Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]", msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w); // ROS_INFO("Vel-> Linear: [%f], Angular: [%f]", msg->twist.twist.linear.x,msg->twist.twist.angular.z); // } // int main(int argc, char **argv) // { // ros::init(argc, argv, "odom_listener"); // ros::NodeHandle n; // ros::Subscriber sub = n.subscribe("odom", 1000, chatterCallback); // ros::spin(); // return 0; // }<file_sep>#include <swarm_navigator/point_cloud_listener.h> #include "ros/ros.h" #include <sensor_msgs/PointCloud2.h> namespace swarm_navigator { /* PointCloudListener implementations */ PointCloudListener::PointCloudListener(ros::NodeHandle &nh,std::string topic){ nh_ = nh; topic_ = topic; } void PointCloudListener::start(){ // subscriber = nh_.subscribe(topic_, 1000, update); subscriber = nh_.subscribe(topic_, 1000, &PointCloudListener::update, this); ros::spin(); } void PointCloudListener::update(const sensor_msgs::PointCloud2ConstPtr& msg){ // seq_ = msg->header.seq; // position_.update( msg->pose.pose.position.x,msg->pose.pose.position.y, msg->pose.pose.position.z); // orientation_.update(msg->pose.pose.orientation.x, msg->pose.pose.orientation.y, msg->pose.pose.orientation.z, msg->pose.pose.orientation.w); // linear_velocity_ = msg->twist.twist.linear.x; // angular_velocity_ = msg->twist.twist.angular.z; // ROS_INFO("Seq: [%d]", seq_); // ROS_INFO("Position-> x: [%f], y: [%f], z: [%f]", position_.getX(),position_.getY(), position_.getZ()); // ROS_INFO("Orientation-> x: [%f], y: [%f], z: [%f], w: [%f]",orientation_.getX(), orientation_.getY(), orientation_.getZ(), orientation_.getW()); // ROS_INFO("Vel-> Linear: [%f], Angular: [%f]", linear_velocity_,angular_velocity_); ROS_INFO("pointcloud recieved______________________"); } } <file_sep>#ifndef CMD_VAL_CONTROLLER_INCLUDE #define CMD_VAL_CONTROLLER_INCLUDE #include <string> #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <geometry_msgs/PoseStamped.h> #include <tf/transform_listener.h> #include <math.h> namespace swarm_navigator { class CmdValController{ private: ros::NodeHandle nh_; ros::Publisher publisher_; tf::TransformListener listener_; std::string base_link_; std::string odom_link_; float liner_velocity_; float angular_velocity_; bool getRobotPose(tf::Stamped<tf::Pose>& global_pose) const; public: CmdValController(ros::NodeHandle &nh,std::string topic); CmdValController(ros::NodeHandle &nh,std::string topic,std::string base_link,std::string odom_link); void stop(); void foward(); void backward(); void left(); void right(); bool driveForward(double distance); bool turn(bool clockwise, double radians); bool achieveGoal(const geometry_msgs::PoseStamped& goal); void setLinerVelocity(float velocity); void setAngularVelocity(float velocity); bool ready(); }; } #endif
ea44413bc48180e7396c8a2eb9f076b2f9db2bc7
[ "C++" ]
7
C++
uomcse13-SwarmRotots/swarm
4411c9974b0a373df6c32ab4f22870700183a1b2
db28549b1329b31647e9691416cd111c6b165a8c
refs/heads/master
<file_sep>package com.firefueled.elitetrader.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Pablo on 24/08/2014. */ public class DBUtil { private SQLiteOpenHelper db; public void init (Context context) { this.db = new MarketOpenHelper(context); } } <file_sep>package com.firefueled.elitetrader.util; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.Predicate; import org.apache.commons.lang3.ArrayUtils; import android.content.Context; import android.util.Log; import com.firefueled.elitetrader.model.BaseModel; import com.firefueled.elitetrader.model.Model; import com.snappydb.DB; import com.snappydb.DBFactory; import com.snappydb.SnappydbException; public class Database { private DB db; private SecureRandom secureRandom; public Database(Context ctx) { try { db = DBFactory.open(ctx, Constants.DB_NAME); secureRandom = new SecureRandom(); } catch (SnappydbException e) { e.printStackTrace(); } } public long getObjectId(){ return secureRandom.nextLong(); } public <T> List<T> all(Class<T> type){ String rawData; String indexKey = getIndexKey(type); String[] keys; ArrayList<T> result = new ArrayList<T>(); try { if(!db.exists(indexKey)) return result; keys = db.getArray(indexKey, String.class); for (String key : keys) { rawData = db.get(key); result.add(fromJSON(type, rawData)); } } catch (SnappydbException e) { e.printStackTrace(); } return result; } public <T> T find(Class<T> type, long id) { return this.find(type, String.valueOf(id)); } public <T> T find(Class<T> type, String id) { String key = getKey(type, id); try { if(!db.exists(key)) return null; String rawData = db.get(key); return fromJSON(type, rawData); } catch (SnappydbException e) { e.printStackTrace(); return null; } } public <T> T save(Class<T> type, T model){ String key = getKey(type, model); try { String rawData = toJSON(type, model); db.put(key, rawData); appendIntoIndex(type, key); return model; } catch (SnappydbException e) { Log.d("WEIRD", "ER"); e.printStackTrace(); return null; } } public <T> List<T> where(Class<T> type, Predicate<T> predicate){ Collection<T> all = all(type); return (List<T>) CollectionUtils.select(all, predicate); } public <T> T findWhere(Class<T> type, Predicate<T> predicate){ List<T> all = where(type, predicate); if (all.size() > 0) return all.get(0); else return null; } public <T> T destroy(Class<T> type, T model){ String key = getKey(type, model); try { if(!db.exists(key)) return null; removeFromIndex(type, key); db.del(key); return model; } catch (SnappydbException e) { e.printStackTrace(); return null; } } public <T> Boolean destroyAll(Class<T> type){ List<T> items = all(type); for (T item : items) { destroy(type, item); } return true; } public <T> String toJSON(Class<T> type, T model){ return Constants.GSON.toJson(model); } public <T> T fromJSON(Class<T> type, String rawData) { return Constants.GSON.fromJson(rawData, type); } private <T> String getTypeName(Class<T> type){ return type.getSimpleName().toLowerCase(Locale.getDefault()); } private <T> String getKey(Class<T> type, Object t){ return getKey(type, ((Model) t).id); } private <T> String getKey(Class<T> type, long t){ return getKey(type, String.valueOf(t)); } private <T> String getKey(Class<T> type, String t){ return getTypeName(type) + "-" + t; } private <T> String getIndexKey(Class<T> type){ return getTypeName(type) + "-keys"; } private <T> void appendIntoIndex(Class<T> type, String key) throws SnappydbException { String indexKey = getIndexKey(type); String[] keys = db.exists(indexKey) ? db.getArray(indexKey, String.class) : new String[0]; db.put(indexKey, ArrayUtils.add(keys, key)); } private <T> void removeFromIndex(Class<T> type, String key) throws SnappydbException { String indexKey = getIndexKey(type); String[] keys = db.exists(indexKey) ? db.getArray(indexKey, String.class) : new String[0]; db.put(indexKey, ArrayUtils.removeElement(keys, key)); } } <file_sep>package com.firefueled.elitetrader.model; import com.firefueled.elitetrader.util.Constants; import com.firefueled.elitetrader.util.Database; import java.util.List; import org.apache.commons.collections4.Predicate; public abstract class Model<T> { private static Database __db = null; private transient Class<T> __type; public long id; public Model(Class<T> type){ if(__db == null){ __db = Constants.DB; } this.id = (int) __db.getObjectId(); this.__type = type; } public List<T> all(){ return __db.all(__type); } public T find(long id) { return __db.find(__type, id); } public T find(String id) { return __db.find(__type, id); } @SuppressWarnings("unchecked") public T save(){ return __db.save(__type, (T) this); } public List<T> where(Predicate<T> predicate){ return __db.where(__type, predicate); } public T findwhere(Predicate<T> predicate){ return __db.findWhere(__type, predicate); } @SuppressWarnings("unchecked") public T destroy(){ return __db.destroy(__type, (T) this); } public Boolean destroyAll(){ return __db.destroyAll(__type); } public String toJSON(T model){ return __db.toJSON(__type, model); } public T fromJSON(String rawData) { return __db.fromJSON(__type, rawData); } }<file_sep>package com.firefueled.elitetrader.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Pablo on 24/08/2014. */ public class MarketOpenHelper extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 2; private static final String DATABASE_NAME = "MARKET"; // STATION public static final String STATION_TABLE_NAME = "STATION"; public static final String KEY_STATION_ID = "ID"; public static final String KEY_STATION_NAME = "NAME"; public static final String KEY_STATION_SYSTEM = "SYSTEM"; private static final String STATION_TABLE_CREATE = "CREATE TABLE " + STATION_TABLE_NAME + " (" + KEY_STATION_ID + " INTEGER PRIMARY KEY ASC, " + KEY_STATION_NAME + " TEXT, " + KEY_STATION_SYSTEM + " TEXT" + ");"; // TRADE ITEM public static final String TRADE_ITEM_TABLE_NAME = "TRADE_ITEM"; public static final String KEY_TRADE_ITEM_ID = "ID"; public static final String KEY_TRADE_ITEM_STATION_ID = "ID_STATION"; public static final String KEY_TRADE_ITEM_NAME = "NAME"; public static final String KEY_TRADE_ITEM_BUY = "BUY"; public static final String KEY_TRADE_ITEM_SELL = "SELL"; private static final String KEY_TRADE_ITEM_ID_CONSTRAINT = "CONSTRAINT TRADE_ITEM_STATION " + "FOREIGN KEY " + KEY_TRADE_ITEM_STATION_ID + " REFERENCES " + STATION_TABLE_NAME + " (" + KEY_TRADE_ITEM_ID + ") " + ""; private static final String TRADE_ITEM_TABLE_CREATE = "CREATE TABLE " + TRADE_ITEM_TABLE_NAME + " (" + KEY_TRADE_ITEM_ID + " INTEGER PRIMARY KEY ASC, " + KEY_TRADE_ITEM_STATION_ID + " INTEGER " + KEY_TRADE_ITEM_ID_CONSTRAINT + ", " + KEY_TRADE_ITEM_NAME + " TEXT, " + KEY_TRADE_ITEM_BUY + " REAL, " + KEY_TRADE_ITEM_SELL + " REAL" + ");"; public MarketOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(STATION_TABLE_CREATE); db.execSQL(TRADE_ITEM_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }<file_sep>EliteTrader =========== This will help you ~~smugle~~ trade ~~stolen cargo~~ needed resources around, accross all the ~~black markets~~ prestigious trading posts. <file_sep>package com.firefueled.elitetrader.model; import java.io.Serializable; /** * Created by Pablo on 24/08/2014. */ public class BaseModel implements Serializable { public long id; }
6c60244fd1afb12cb38b47aff4d1e5023446d595
[ "Markdown", "Java" ]
6
Java
Slpk/EliteTrader
321b80615a8a113514bb510f628a9f1af9d6d020
fb27d8a0a677b8d7d7eae20d3d3165237e83cc0a
refs/heads/master
<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> using namespace std ; class Converter{ public: string DUMMY ; Converter(){ DUMMY = "dumVal"; } string integerToString(int x){ int a = x; stringstream ss; ss << a; string str = ss.str(); return str ; } string floatToString(float x){ float a = x; stringstream ss; ss << a; string str = ss.str(); return str ; } int stringToInteger(string s){ if(s == "NOT_GIVEN_YET"){ return -1 ; } stringstream geek(s); int x = 0; geek >> x; return x; } float stringToFloat(string s){ stringstream geek(s); float x = 0; geek >> x; return x; } string boolToString(bool x){ bool a = x; stringstream ss; ss << a; string str = ss.str(); return str ; } bool stringToBool(string s){ stringstream geek(s); bool x = 0; geek >> x; return x; } string makeName(string name1, string name2){ return (name1 + "_" + name2); } std::vector<std::string> splitString(const std::string& a, char delim) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(a); while (std::getline(tokenStream, token, delim)) { tokens.push_back(token); } return tokens; } }; class FunResult{ public: string funName; string resName; FunResult(){ } FunResult(string f, string r){ funName = f; resName = r; } FunResult(const FunResult &f){ funName = f.funName; resName = f.resName; } string getFunResult(){ return ("funName : " + funName + " , resName : " + resName + "\n"); } };<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include "1505022_PairItems.h" using namespace std ; class ArrayItems { public: bool isArray ; string arrayName; int lineNumberBegin ; int size ; vector<PairItems> arrayValues; ArrayItems() { lineNumberBegin = -1; size = -1; arrayName = "NIL"; isArray = false ; } std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } /* void addValue(string s){ PairItems pair(-1, s); this->arrayValues.push_back(pair); } */ bool addValue(int i, string s){ printf("INSIDE addValue ... i = %d, s = ", i); cout << s ; if(i >= size){ return false ; } if(i < 0){ return false; } PairItems pair(i, s); cout << pair.getString() << endl ; //this->arrayValues.push_back(pair); //this->arrayValues.push_back(pair); return true; } string getArrayValues(){ string s = ""; for(int i=0; i<(int)arrayValues.size(); i++){ s += "(" ; s += arrayValues[i].getString(); s += ") "; } s += "\n"; return s ; } string getArrayItem(){ string s = "\n-----------------------------------------------------\n"; s += "arrayName = " ; s += arrayName ; s += " , size = "; s += getString(size) ; s += " , lineNumberBegin = "; s += getString(lineNumberBegin); s += "\nArrayValues = "; s += getArrayValues(); s += "\n-----------------------------------------------------\n"; return s ; } void printArrayItem( ) { string s = getArrayItem(); cout << s ; } void makeArray(string name, int s, int lineNum) { arrayName = name; this->size = s ; lineNumberBegin = lineNum; isArray = true ; } void changeArray(ArrayItems arr2){ this->isArray = arr2.isArray; this->arrayName = arr2.arrayName; this->lineNumberBegin = arr2.lineNumberBegin; this->size = arr2.size ; this->arrayValues.clear(); for(int i=0; i<(int)arr2.arrayValues.size(); i++){ this->arrayValues[i].index = arr2.arrayValues[i].index; this->arrayValues[i].value = arr2.arrayValues[i].value; } } bool equals(ArrayItems ar2){ if(this->isArray != ar2.isArray) return false; if(this->arrayName != ar2.arrayName) return false; if(this->lineNumberBegin != ar2.lineNumberBegin) return false; if(this->size != ar2.size) return false; if(this->arrayValues.size() != ar2.arrayValues.size()) return false; for(int i=0; i<(int) arrayValues.size(); i++){ PairItems p1 = arrayValues[i]; PairItems p2 = ar2.arrayValues[i]; if(p1.index != p2.index) return false; if(p1.value != p2.value) return false; } return true; } }; class Variable { public: string name; string type; string actualValue; string symbol; string code ; int lineBegin ; bool isArray ; void setVariable(Variable v){ name = v.name; type = v.type; lineBegin = v.lineBegin; isArray = v.isArray; symbol = v.symbol; code = v.code ; } Variable() { name = "NIL" ; type = "NIL" ; isArray = false ; } Variable(string n, string t, int l, string ac, string symbol1, string code1 ) { name = n; type = t; lineBegin = l; actualValue = ac; isArray = false ; symbol = symbol1; code = code1; } Variable(string n, string t, int l, string ac, string symbol1) { name = n; type = t; lineBegin = l; actualValue = ac; isArray = false ; symbol = symbol1; } Variable(string n, string t, int l, string ac ) { name = n; type = t; lineBegin = l; actualValue = ac; isArray = false ; } Variable(string n, string t, int l) { name = n; type = t; lineBegin = l; isArray = false ; } std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } std::string getString ( bool Number ) { std::ostringstream ss; ss << Number; return ss.str(); } string getVariable( ) { string s = "<<Name = " + name + " , Type = " + type + " symbol : " + symbol ; s += " , line = "; s += getString(lineBegin); s += ">>\n" ; return s; } string getVariableForArg(){ string s = "<<Name = " + name + " , Type = " + type ; s += " , line = "; s += getString(lineBegin); s += " , actualValue = "; s += actualValue; s += " , isArray = "; s += getString(isArray) ; s += " , symbol = "; s += symbol ; s += ">>\n" ; return s; } void printVariable( ) { string s = getVariable(); cout << s ; } void makeVariable(string n, string t, int l) { name = n; type = t; lineBegin = l; } }; class FunctionItems { private: //ofstream funOut ; public: bool isFunction ; string functionName ; int numberParameters; int lineNumberBegin; int lineNumberEnd ; string returnType; string declareOrDefine ; vector<Variable> list; //ofstream out ; FunctionItems(){ isFunction = false; functionName = "NIL"; numberParameters = -1; lineNumberBegin = -1; lineNumberEnd = -1; returnType = "NIL"; declareOrDefine = "NIL"; //funOut.open("Function_Debug.txt"); } void changeFunction(FunctionItems f){ printf("Inside change function .. printing parameter's function : \n"); cout << f.getFunction() << endl ; this->isFunction = f.isFunction; this->functionName = f.functionName; this->numberParameters = f.numberParameters; this->lineNumberBegin = f.lineNumberBegin; this->lineNumberEnd = f.lineNumberEnd; this->returnType = f.returnType; this->declareOrDefine = f.declareOrDefine; int x = (int)this->list.size(); if(x >= 1){ this->list.clear(); } cout << "MIDDLE SETTING!!\n"; for(int i=0; i<(int)f.list.size(); i++){ Variable var(f.list[i].name, f.list[i].type, f.list[i].lineBegin, f.list[i].symbol); //Variable var(); //var.setVariable(f.list[i]); list.push_back(var); } cout << "AFTER SETTING!!\n"; cout << this->getFunction() << endl ; } string equals(FunctionItems f2) { if(this->returnType != f2.returnType){ string s = "Return types do not match \n"; s += f2.declareOrDefine ; s += " at line. "; s += getString(f2.lineNumberBegin); s += " is " ; s += f2.returnType ; s += " AND "; s += this->declareOrDefine ; s += " at line."; s += getString(this->lineNumberBegin); s += " is "; s += this->returnType; return s ; } if(this->numberParameters != f2.numberParameters){ string s = "Number of parameters do not match \n"; s += "Number of parameters is "; s += getString(f2.numberParameters); s += " at line. "; s += getString(f2.lineNumberBegin); s += " AND , number of parameters is "; s += getString(this->numberParameters); s += " at line. "; s += getString(this->lineNumberBegin); return s ; } for(int i=0; i<(int)list.size(); i++){ Variable v1 = list[i]; Variable v2 = f2.list[i]; if(v1.type != v2.type){ string s = "Data Types of parameter list do not match of declared and defined , example ... \n" ; s += "At " ; s += f2.declareOrDefine ; s += " is '" ; string x12 = v2.type; transform(x12.begin(), x12.end(), x12.begin(), ::tolower); s += x12 ; s += " " ;s += v2.name ; s += "' AND at " ; s += this->declareOrDefine ; s += " is '" ; x12 = v1.type; transform(x12.begin(), x12.end(), x12.begin(), ::tolower); s += x12 ; s += " "; s += v1.name; s+="'\n" ; return s ; } } return "Matched" ; } std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } void printFunction() { string s = getFunction(); cout << s ; } string getFunction() { string s = "\n-----------------------------------------------------\n"; s += "functionName = " ; s += functionName ; s += " , numberParameters = "; s += getString(numberParameters) ; s += " , list size = " ; s += getString(list.size()); s += "\n"; s += " , lineNumberBegin = "; s += getString(lineNumberBegin); s += " , lineNumberEnd = "; s += getString(lineNumberEnd); s += " , returnType = " ; s += returnType ; s += " , declareOrDefine = "; s += declareOrDefine ; s += "\n"; for(std::vector<Variable> :: iterator it = list.begin(); it != list.end(); it++){ Variable var = *it; s += var.getVariableForArg(); } s += "\n-----------------------------------------------------\n"; return s ; } void addFunctionItem(Variable var){ list.push_back(var); } void addFunctionItem(string name, string type, int beginLine){ Variable var(name, type, beginLine); list.push_back(var); } Variable getNode(string name) { Variable node; vector<Variable> :: iterator it = list.begin(); for (; it != list.end(); it++) { Variable var = *it ; if(var.name == name) return node ; } return node ; } bool doesExist(string name) { Variable node ; node = getNode(name); if((node.name == "NIL") && (node.type == "NIL")) return true ; return false ; } void makeFunction(string funName, string rT,int numberParameters, int lineBegin, int lEnd) { this->functionName = funName ; this->numberParameters = numberParameters; this->lineNumberBegin = lineBegin; this->lineNumberEnd = lEnd; this->returnType = rT ; } }; class ArgumentList { public: string functionName; vector <Variable> listArguments; ArgumentList(){ } void addArgument(string name, string type, int lineNumberBegin, string actualValue, bool isArray,string symbol, string code){ Variable pair(name, type, lineNumberBegin, actualValue, symbol, code); pair.isArray = isArray ; listArguments.push_back(pair); } void addArgument(string name, string type, int lineNumberBegin, string actualValue, string symbol){ Variable pair(name, type, lineNumberBegin, actualValue, symbol); pair.isArray = false ; listArguments.push_back(pair); } void addArgument(string name, string type, int lineNumberBegin, string actualValue, bool flag, string symbol){ Variable pair(name, type, lineNumberBegin, actualValue, symbol); pair.isArray = flag ; listArguments.push_back(pair); } void addArgument(string name, string type, int lineNumberBegin, string actualValue, bool flag ){ Variable pair(name, type, lineNumberBegin, actualValue); pair.isArray = flag ; listArguments.push_back(pair); } void addArgument(string name, string type, int lineNumberBegin, string actualValue){ Variable pair(name, type, lineNumberBegin, actualValue); listArguments.push_back(pair); } Variable getArgument(string name){ Variable pair; for(int i=0; i<(int)listArguments.size(); i++){ pair = listArguments[i]; if(pair.name == name) return pair ; } return pair ; } string getArgumentList(){ string s = "\nFunctionName ="; s += functionName; s += "\nPrinting all arguments:\n"; for(int i=0; i<(int)listArguments.size(); i++){ s += listArguments[i].getVariableForArg(); s += " "; } s += "\n"; return s; } void clear(){ if(listArguments.size() > 0){ listArguments.clear(); } } };<file_sep>int f(int a); int f2(); int main(){ int x; x = f(7); println(x); x = f2(); println(x); } int f(int a){ return a; } int f2(){ return -7; }<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include <streambuf> #include <set> #include"../Miscalenous/Converter.h" using namespace std ; class Optimizer{ public: ofstream code; ofstream code2; ofstream deb ; ifstream input; Converter converter ; std::vector<string> finalLines; std::vector<string> lines; std::vector<string> ekdomFinalLines; int currentIndex; int untilDotIndex; int line ; Optimizer(){ code.open("IntermediateCodeStuffs/OptimizedCodes/OptimizedCode.asm"); deb.open("IntermediateCodeStuffs/OptimizedCodes/OptimizedDeb.txt"); code2.open("IntermediateCodeStuffs/OptimizedCodes/1505022.asm"); input.open("IntermediateCodeStuffs/ICode.asm"); currentIndex = -1; line = 0; } void optimize(){ printf("=>Inside Optimze ...\n\n"); retrieveInput(); removeNewLinesExtra(); removeComments(); processCode(); removeConsecutiveSameCode(); printFullCode(); } bool contains(string str, string str2){ if (str.find(str2) != string::npos) { //.. found. return true; } return false ; } std::vector<std::string> splitString(const std::string& a, char delim) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(a); while (std::getline(tokenStream, token, delim)) { tokens.push_back(token); } return tokens; } void retrieveInput(){ std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>()); //deb << str << endl << endl ; lines = splitString(str, '\n'); } bool isValidForKeyWords(string line) { int size = 9; string keyWords[size] = {".DATA", ".CODE", ".MODEL", ".STACK", "RET", "PROC", "ENDP", "MAIN", ":"}; for(int i=0; i<size; i++){ if(contains(line, keyWords[i]) == true) return true; } return false ; } bool isValid(string line){ bool flag = false ; if(line == "\n"){ flag = true; } else{ //flag = isValidForKeyWords(line); if(isValidForKeyWords(line) == true){ flag = true; }else{ //Check for comments in Icode. } } return flag ; } int actuallyPrintUntilDot(){ printDeb("==================[[[[ Inside actuallyPrintUntilDot begins ]]]===================="); int size = (int)lines.size(); printDeb("Size of lines vector is " + converter.integerToString(size)); for(int i=0; i<size; i++){ string line = lines[i]; printDeb("Line is " + line); if(line != ".CODE"){ finalLines.push_back(lines[i]); ekdomFinalLines.push_back(lines[i]); } else if(line == ".CODE"){ finalLines.push_back(lines[i]); ekdomFinalLines.push_back(lines[i]); return (i+1); } } printDeb("==================[[[[ Inside actuallyPrintUntilDot ends ]]]===================="); } bool checkIfSameCode(string ins1, string ins2){ ins1 = getTrimmedName(ins1); ins2 = getTrimmedName(ins2); ins1 = removeComment(ins1); ins2 = removeComment(ins2); printDeb("INSIDE checkIfSameCode ... "); printDeb("ins1 = |" + ins1 + "|"); printDeb("ins2 = |" + ins2 + "|"); if(ins1 == ins2){ return true; } else{ return false ; } } void removeConsecutiveSameCode(){ int size = (int)finalLines.size(); int i = untilDotIndex; while(i < size){ string line = finalLines[i]; printDeb("==>removeConsecutiveSameCode, Line got is |" + line + "|"); if(isValid(line)){ ekdomFinalLines.push_back(line); printDeb("-->>removeConsecutiveSameCode, Line is valid so i++ , line is |" + line + "|"); i++; } else{ string thisInstruction = finalLines[i]; string nextInstruction = finalLines[i+1]; bool flag = checkIfSameCode(thisInstruction, nextInstruction); if(flag == true){ //Peephole condition occured !! //Get Rid of BOTH Conditions.. ekdomFinalLines.push_back(thisInstruction); i += 2; } else{ i++ ; //Push THIS instruction ekdomFinalLines.push_back(thisInstruction); } } } printDeb("AFTER removeConsecutiveSameCode , printing vector .. ekdomFinalLines "); printVector(ekdomFinalLines); } void processCode(){ printDeb("====================processCode begins======================"); int size = (int)lines.size(); untilDotIndex = actuallyPrintUntilDot(); int i = untilDotIndex ; printDeb("=============>>>>>Upto actuallyPrintUntilDot ... printing the lines .. untilDotIndex = " + converter.integerToString(untilDotIndex)); printVector(); printDeb("Going into while loop, i = " + converter.integerToString(i) + " and size = " + converter.integerToString(size)); while(i < size){ string line = lines[i]; printDeb("==>Line got is |" + line + "|"); if(isValid(line)){ finalLines.push_back(line); printDeb("-->>Line is valid so push and i++ , line is |" + line + "|"); i++; } else{ string thisInstruction = lines[i]; string nextInstruction = lines[i+1]; bool isPeepHole = checkIfPeepholeHasOccured(thisInstruction, nextInstruction); if(isPeepHole == true){ //Peephole condition occured !! //Get Rid of 2nd Condition.. printDeb("-->>Peephole occured for |" + thisInstruction + "| and |" + nextInstruction + "|"); string inst_with_comment = thisInstruction + ("\t\t;Peephole occured with " + nextInstruction); finalLines.push_back(inst_with_comment); //Just push 1st instruction i += 2; } else if(isPeepHole == false){ i++ ; //Push THIS instruction printDeb("-->>Peephole not occured for |" + thisInstruction + "|"); finalLines.push_back(thisInstruction); } } } printDeb("AFTER PROCESS , printing vector .. "); printVector(finalLines); } bool isComment(string s){ s = getTrimmedName(s); if(s == ""){ return true; } if(s[0] == ';'){ return true; } return false ; } string getNextInstruction(int currentIdx){ for(int i=currentIdx+1; i<(int)lines.size(); i++){ if(lines[i] == "\n"){ //Do Nothing }else{ return lines[i]; } } return "\nNOTHING_DONE\n"; } string getTrimmedName(string s) { string str = ""; int idx = 0; for(int i=0; i<s.length(); i++){ if((s[i]!=' ') && (s[i] != '\t')){ idx = i; break ; } } for(int i=idx; i<s.length(); i++){ str += s[i]; } return str ; } bool isMove(string s){ s = getTrimmedName(s); if(s == "\n"){ return false ; } if(s == ""){ return false ; } if(s == "\t"){ return false ; } if(contains(s, "MOV") == true){ return true ; } return false ; } string removeComment(string s){ string str = ""; for(int i=0; i<s.length(); i++){ if(s[i] == ';'){ break; }else{ str += s[i]; } } return str ; } bool checkForConditionConsecInstr(string ins1, string ins2){ std::vector<string> arr1 = splitString(ins1, ' '); std::vector<string> arr2 = splitString(ins2, ' '); printDeb("---->>>Inside checkForConditionConsecInstr ... printing arr1 and arr2"); printDeb("arr1 size is " + converter.integerToString((int)arr1.size())); for(int i=0; i<(int)arr1.size(); i++){ arr1[i] = removeComma(arr1[i]); printDeb(arr1[i]); } printDeb("arr2 size is " + converter.integerToString((int)arr2.size())); for(int i=0; i<(int)arr2.size(); i++){ arr2[i] = removeComma(arr2[i]); printDeb(arr2[i]); } string leftReg1, rightReg1, leftReg2, rightReg2 ; leftReg1 = arr1[1]; rightReg1 = arr1[2]; leftReg2 = arr2[1]; rightReg2 = arr2[2]; printDeb("++>>PRINTING leftReg1 = |" + leftReg1 + "| equal to rightReg2 = |" + rightReg2 + "|"); printDeb("and leftReg2 =|" + leftReg2 + "| equal to rightReg1 = |" + rightReg1 + "|"); if((leftReg1 == rightReg2) && (leftReg2 == rightReg1)){ //printDeb("return true since leftReg1 = " + leftReg1 + " equal to rightReg2 = " + rightReg2); //printDeb("and leftReg2 = " + leftReg2 + " equal to rightReg1 = " + rightReg1); printDeb("Return true from checkForConditionConsecInstr"); return true ; } printDeb("Return FALSE from checkForConditionConsecInstr"); return false; } bool checkPeeophole(string thisInstruction, string nextInstruction){ printDeb("===>>> Inside checkPeeophole for two instructions ... "); if(thisInstruction == ""){ return false ; } if(nextInstruction == ""){ return false; } string trim1 = getTrimmedName(thisInstruction); string trim2 = getTrimmedName(nextInstruction); trim1 = removeComment(trim1); trim2 = removeComment(trim2); //trim1 = removeTrails(trim1); //trim2 = removeTrails(trim2); printDeb("1st :" + trim1); printDeb("2nd :" + trim2); if(contains(trim1, "MOV") && contains(trim2, "MOV")){ return checkForConditionConsecInstr(trim1, trim2); } return false ; } bool checkIfPeepholeHasOccured(string thisInstruction, string nextInstruction){ if((isMove(thisInstruction)==false) || (isMove(thisInstruction)==false)){ return false ; } printDeb("==================================================================================="); printDeb("First Inst : " + thisInstruction); printDeb("Second Inst: " + nextInstruction); bool checker = checkPeeophole(thisInstruction, nextInstruction); if(checker){ printDeb("Checker is True => Eliminate Both "); }else{ printDeb("Checker is False => Keep both "); } printDeb("==================================================================================="); return checker ; } int getIndexOfDot(){ int size = (int)lines.size(); for(int i=0; i<size; i++){ string line = lines[i]; if(line != ".CODE"){ } else if(line == ".CODE"){ return (i+1); } } } string get(string s){ return ("|" + s + "|"); } void removeComments(){ std::vector<string> v; printDeb("=================<<<removeComments Begin>>>>============================"); for(int i=0; i<(int)lines.size(); i++){ //lines[i] = getTrimmedName(lines[i]); string line = lines[i]; string s = "Line Found is " + get(line); if(isComment(lines[i])){ //printDeb("-->>Line is a comment so i++ , line is |" + lines[i] + "|"); s += (" ,,, Line is a comment so simply do nothin \n"); }else{ //printDeb("===>>Pushing back line: " + get(lines[i])); s += (" ,,, Push back the line \n"); v.push_back(lines[i]); } s += "\n"; //printDeb(s); } //printDeb("-->>>Size of v: " + converter.integerToString((int)v.size())); for(int i=0; i<(int)v.size(); i++){ //printDeb(v[i]); } lines.clear(); for(int i=0; i<(int)v.size(); i++){ lines.push_back(v[i]); } printDeb("AFTER removeComments .. printing vectror"); printVector(lines); printDeb("=================<<<removeComments ENDS>>>>============================"); } string removeExtraLine(string s){ string str = ""; for(int i=0; i<s.length(); i++){ if(s[i] == '\n'){ break; } else{ str += s[i]; } } return str ; } void printVector(std::vector<string> v){ printDeb("-----------------------------------------------------------------------------------------"); printDeb("Printing vector v. size = " + converter.integerToString((int)v.size())); for(int i=0; i<(int)v.size(); i++){ printDeb(v[i]); } printDeb("-----------------------------------------------------------------------------------------"); } void printVector(){ printDeb("-----------------------------------------------------------------------------------------"); printDeb("Printing finalLines . size = " + converter.integerToString((int)finalLines.size())); for(int i=0; i<(int)finalLines.size(); i++){ printDeb(finalLines[i]); } printDeb("-----------------------------------------------------------------------------------------"); } void printFullCode(){ for(int i=0; i<(int)finalLines.size(); i++){ string line = indent(finalLines[i]); line = removeExtraLine(line); //line = removeTrails(line); code << line << endl; } for(int i=0; i<(int)ekdomFinalLines.size(); i++){ string line = indent(ekdomFinalLines[i]); line = removeExtraLine(line); //line = removeTrails(line); code2 << line << endl; } } bool isWhiteSpace(string s){ for(int i=0; i<s.length(); i++){ if((s[i] != ' ')){ if(s[i] != '\n'){ if(s[i] != '\t'){ return false ; } } } } return true; } void removeNewLinesExtra(){ std::vector<string> v; for(int i=0; i<(int)lines.size(); i++){ //printDeb("===>>>Line is |" + lines[i] + "|\n\n"); lines[i] = getTrimmedName(lines[i]); //lines[i] = removeTrails(lines[i]); if((lines[i] == "\n") || (lines[i] == "") || (isWhiteSpace(lines[i]))){ //Do Nothing } else{ v.push_back(lines[i]); } } printDeb("-->>>Size of v: " + converter.integerToString((int)v.size())); for(int i=0; i<(int)v.size(); i++){ printDeb(v[i]); } lines.clear(); for(int i=0; i<(int)v.size(); i++){ lines.push_back(v[i]); } } string removeTrails(string s){ string str = ""; s = getTrimmedName(s); for(int i=0; i<s.length(); i++){ if((s[i] == ' ') || (s[i] == '\t') || (s[i] == '\n')){ //Normal letters... break; } else{ //White space encountered str += s[i]; } } return str ; } string removeComma(string s){ string str = getTrimmedName(s); string ans = ""; for(int i=0; i<str.length(); i++){ if(str[i] == ','){ break; } else{ ans += str[i]; } } ans = removeTrails(ans); return ans ; } string indent(string s){ if(isValid(s) == true){ return s ; } vector<string> line = converter.splitString(s, '\n'); string res = ""; for(int i=0; i<(int)line.size(); i++){ string str = line[i]; string s1 = "\t" + str + "\n"; res += s1; } return res; } void printDeb(string s){ deb << s << endl ; //cout << s << endl; } }; <file_sep> int main(){ int i, c, b ; //Program finds max and the index of the max element of the array. int max; max = -1; int a[10]; for(i=0; i<10; i++){ a[i] = (i * 10); } for(i=0; i<10; i++){ b = a[i]; println(b); } for(i=0; i<10; i++){ if(a[i] >= max){ max = a[i]; c = i; } } println(max); println(i); } <file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include "../Miscalenous/1505022_Items.h" #define prime_number 13 #define dummy "dummy" using namespace std ; class SymbolInfoNode { public: string symbol_name; //key used for hash table. string symbol_type; SymbolInfoNode *next; int line_number_begin = -1; int line_number_end = -1; string code; string symbol; ArrayItems arrayItems ; FunctionItems functionItems ; bool isFunction = false; bool isArray = false; string dataType = "NIL"; // HOW TO GET ??? string faceValue = "UNDEFINED"; string actualValue = "NOT_GIVEN_YET"; std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } std::string getString ( bool Number ) { std::ostringstream ss; ss << Number; return ss.str(); } // Overloading of Assignment Operator void operator=(const SymbolInfoNode &node) { printf("Inside operator[1] = \n"); } void operator =(const SymbolInfoNode *node){ printf("Inside operator = \n"); } //Constructor SymbolInfoNode(string n, string t, int line, string s, string c, bool isA, bool isF, string d){ setName(n); setType(t); this->line_number_begin = line ; this->line_number_end = line ; setDataType(d); next = 0 ; this->isArray = isA; this->isFunction = isF; this->code = c; this->symbol = s ; } SymbolInfoNode(string name, string type, int line , string data) { setName(name); setType(type); this->line_number_begin = line ; this->line_number_end = line ; setDataType(data); next = 0 ; isArray = false; isFunction = false; } SymbolInfoNode(string name, string type, int line ) { setName(name); setType(type); this->line_number_begin = line ; this->line_number_end = line ; next = 0 ; isArray = false; isFunction = false; } SymbolInfoNode(string name, string type, int line, int line2 ) { setName(name); setType(type); this->line_number_begin = line ; this->line_number_end = line2 ; next = 0 ; isArray = false; isFunction = false; } SymbolInfoNode(string name, string type) { setName(name); setType(type); next = 0 ; isArray = false; isFunction = false; } SymbolInfoNode() { setName(dummy); setType(dummy); next = 0; isArray = false; isFunction = false; } bool isDummy() { if(symbol_name == dummy && symbol_type == dummy) return true ; return false ; } SymbolInfoNode(string name, string type, SymbolInfoNode *next_pointer) { setName(name); setType(type); next = 0 ; next = next_pointer ; isArray = false; isFunction = false; } //Destructor ~SymbolInfoNode() { // //printf("==-->>Calling Destructor for Node = "); printNode(); deleteNextNode(); } //Getter and Setter void setName(string name) { symbol_name = name; symbol = ""; code = ""; } void setType(string type) { symbol_type = type; } string getName() { return symbol_name; } string getType() { return symbol_type; } void setLineBegin(int line) { this->line_number_begin = line ; } int getLineBegin() { return this->line_number_begin ; } void setDataType(string s) { this->dataType = s ; } void setDataType(SymbolInfoNode *node){ this->dataType = node->getDataType(); } string getDataType() { return this->dataType ; } void setLineEnd(int line) { line_number_end = line ; } int getLineEnd(){ return line_number_end; } //GETTER AND SETTER DONE void deleteNextNode() { if(next) delete next ; next = 0; } void printNode() { cout << "<" << symbol_name << " : " << symbol_type << ">" << endl ; } void printNodeB() { cout << "<" << symbol_name << " ::: " << symbol_type << ">" << " , line begin = " << line_number_begin << " , line end = " << line_number_end << " , dataType = " << dataType << endl ; } void printForTable() { cout << "<" << symbol_name << " : " << symbol_type << ">" << " " ; } //Comparison Operator Overload. bool equals(SymbolInfoNode *node1){ //printf("======+<<<<????<<<< INSIDE Comparison Operator >>>>>>?????>>>>>++=========\n"); //printf("PRINTING THIS NODE ... \n"); cout << this->getPrintForTable(); //printf("PRINTING node1...\n"); cout << node1->getPrintForTable(); if(symbol_name != node1->symbol_name){ //printf("symbol_name != node1.symbol_name\n"); return false; } if(symbol_type != node1->symbol_type){ //printf("symbol_type != node1.symbol_type\n"); return false; } if(dataType != node1->dataType){ //printf("dataType != node1.dataType\n"); return false; } if(false){ ///ACTUAL VALUE NOT CHECKING... //printf("actualValue != node1.actualValue\n"); return false; } if(isArray != node1->isArray){ //printf("isArray != node1.isArray\n"); return false; } if(isFunction != node1->isFunction){ //printf("isFunction != node1.isFunction\n"); return false; } if(functionItems.list.size() != node1->functionItems.list.size()){ //printf("functionItems.list.size() donet match\n"); return false; } if(line_number_begin != node1->line_number_begin){ //printf("line_number_begin dont match"); return false; } if(line_number_end != node1->line_number_end){ //printf("line_number_end dont match \n"); return false ; } FunctionItems f1 = this->functionItems; FunctionItems f2 = node1->functionItems; if(f1.equals(f2) != "Matched"){ //printf("FunctionItems dont match\n"); return false; } if(arrayItems.equals(node1->arrayItems) == false){ //printf("ArrayItems dont match\n"); return false; } return true; } void setSymbol(SymbolInfoNode *node2) { this->symbol_name = node2->getName(); this->symbol_type = node2->getType(); this->line_number_begin = node2->getLineBegin(); this->line_number_end = node2->getLineEnd(); this->dataType = node2->dataType ; this->symbol = node2->symbol; this->code = node2->code; } void setUnion(string s) { this->symbol_name += s ; } void setUnion(SymbolInfoNode *node1) { this->symbol_name += node1->getName(); this->line_number_begin = max(this->line_number_begin, node1->getLineBegin()); this->line_number_end = max(this->line_number_end, node1->getLineEnd()); this->dataType = node1->dataType ; this->actualValue = node1->actualValue; this->code += node1->code ; } void setSymbol(SymbolInfoNode *node1, SymbolInfoNode *node2) { this->symbol_name = node1->getName(); this->line_number_begin = node1->getLineBegin(); this->line_number_end = node1->getLineEnd(); this->symbol = node1->symbol; this->code = node1->code; this->code += node2->code ; this->symbol_name += " "; this->symbol_name += node2->getName(); this->line_number_begin = max(this->line_number_begin, node2->getLineBegin()); this->line_number_end = max(this->line_number_end, node2->getLineEnd()); } void setSymbol(SymbolInfoNode *node1, SymbolInfoNode *node2, SymbolInfoNode *node3) { this->symbol_name = node1->getName(); this->line_number_begin = node1->getLineBegin(); this->line_number_end = node1->getLineEnd(); this->symbol = node1->symbol; this->code = node1->code; this->code += node2->code ; this->code += node3->code; this->symbol_name += " "; this->symbol_name += node2->getName(); this->line_number_begin = max(this->line_number_begin, node2->getLineBegin()); this->line_number_end = max(this->line_number_end, node2->getLineEnd()); this->symbol_name += " "; this->symbol_name += node3->getName(); this->line_number_begin = max(this->line_number_begin, node3->getLineBegin()); this->line_number_end = max(this->line_number_end, node3->getLineEnd()); } void setSymbol(vector<SymbolInfoNode *> list) { this->symbol_name = "" ; this->line_number_end = 0; this->line_number_begin = 0; for(int i=0; i<list.size(); i++) { this->symbol_name += " "; this->symbol_name += list[i]->getName(); this->line_number_begin = max(this->line_number_begin, list[i]->getLineBegin()); this->line_number_end = max(this->line_number_end, list[i]->getLineEnd()); } } void makeNode(SymbolInfoNode *node){ this->symbol_name = node->symbol_name; this->symbol_type = node->symbol_type; this->line_number_begin = node->line_number_begin; this->line_number_end = node->line_number_end; this->symbol = node->symbol; this->code = node->code; this->dataType = node->dataType; this->isArray = node->isArray; this->isFunction = node->isFunction; this->actualValue = node->actualValue; this->faceValue = node->faceValue; this->functionItems.changeFunction(node->functionItems); this->arrayItems.changeArray(node->arrayItems); } string getForTabFinally() { if(symbol_name == dummy) return 0 ; string s = "<" ; s = s + symbol_type; s = s + " :: "; s = s + symbol_name ; s = s + ">"; return s ; } string getPrintForTable() { //return getForTabFinally(); if(symbol_name == dummy) return 0 ; string s = "<{[ type=" ; s = s + symbol_type; s = s + " ::: name ="; s = s + symbol_name ; s = s + " ::: dataType ="; s = s + dataType ; s += " ::: symbol = "; s += symbol ; s += " ::: \ncode = "; s += code ; s += " :: line num beg = "; s += getString(line_number_begin); s += " ::: isArray = "; s += getString(isArray) ; s += " :: isFunction = "; s += getString(isFunction) ; s = s + "]}>"; return s ; } string getEverything_3(){ if(symbol_name == dummy) return 0 ; string s = "<{[ type=" ; s = s + symbol_type; s = s + " ::: name ="; s = s + symbol_name ; s = s + " ::: dataType ="; s = s + dataType ; s += " ::: actualValue = "; s += actualValue ; s += " :: line num beg = "; s += getString(line_number_begin); s += " ::: isArray = "; s += getString(isArray) ; s += " :: isFunction = "; s += getString(isFunction) ; s = s + "]}>"; if(isFunction == true){ s += functionItems.getFunction(); } if(isArray == true){ s += arrayItems.getArrayItem(); } return s ; } SymbolInfoNode *makeNewNode(string name, string type) { SymbolInfoNode *node = new SymbolInfoNode(name, type); node->next = 0; return node ; } void printLinkedList(SymbolInfoNode *head){ while(head->next != 0){ if(head->isDummy() == true){ head = head->next; } else{ head->printForTable(); //printf(" "); head = head->next; } } } SymbolInfoNode *getNext(){return next;}; void setNext(SymbolInfoNode *next_ptr) { // deleteNextNode(); next = next_ptr; } }; <file_sep>clear clear clear clear clear clear clear clear g++ -o outOpt.out IntermediateCodeStuffs/OptimizerRunner.cpp ./outOpt.out <file_sep>int globalVariable; int fun1(int a, int b){ return (a - b); } void f(int b){ b--; } int main(){ int x, i; x = fun1(5, 1); println(x); } <file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include <streambuf> #include <set> //#include "../Miscalenous/Converter.h" #include "../Bison_Stuffs/1505022_SemanticUtil.h" using namespace std ; class IUtil{ public: std::vector<string> codeLines; std::vector<string> mainLines; std::vector<string> dataLines; std::vector<string> otherFunctions; std::set<string> dataSet ; std::vector<SymbolInfoNode *> argumentsOfFunction; std::vector<SymbolInfoNode *> parametersOfFunction; std::vector<FunResult> funResults; std::vector<SymbolInfoNode *> declaredVariables; string currentResultVar; string currentFunName; ofstream codeOut ; ofstream main; ofstream data; ofstream deb ; ofstream fun; ifstream input; string code ; Converter converter ; int labelNum = 0; int tempNum = 0; int resNum = 0; int mainTab = 0; bool doPrint = true; void pushArgument(SymbolInfoNode *node){ SymbolInfoNode *src = new SymbolInfoNode(); setSymbol(src, node); this->argumentsOfFunction.push_back(src); } IUtil(){ codeOut.open("IntermediateCodeStuffs/ICode.asm"); main.open("IntermediateCodeStuffs/Main.asm"); data.open("IntermediateCodeStuffs/Data.asm"); deb.open("IntermediateCodeStuffs/DEBUG.txt"); input.open("IntermediateCodeStuffs/InputFunctions.asm"); fun.open("IntermediateCodeStuffs/OutFunctions.asm"); printInitialCode(); } void printPrintFunction(){ std::string str((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>()); fun << str << endl << endl ; otherFunctions.push_back(str + "\n\n"); } void setUtils(const BisonUtil &b, const SemanticUtil &s){ //butil.printSemantic("SIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIUUUU!!\n"); } void printCode(string s){ codeLines.push_back(s); codeOut << s << endl ; if(doPrint){ cout << s << endl ; } } void printInitialCode(){ string initial = ".DATA"; //printData(initial); makeVar("primary_variable"); printPrintFunction(); } void printData(string s){ if(s == ".DATA"){ return; } //data << "\t" << s << endl ; dataLines.push_back("\t" + s); dataSet.insert("\t" + s); if(doPrint){ cout << "\t" << s << endl ; } } void printMain(string s){ if(false){ main << s << endl ; if(doPrint){ cout << s << endl ; } }else{ mainLines.push_back(s); main << s << endl ; if(doPrint){ cout << s << endl ; } } } void printDeb(string s, bool flag){ deb << s << endl; if(flag){ cout << s << endl ; } } void printDeb(string s){ printDeb(s, true); } string getTabMain(int t){ string s = ""; for (int i = 0; i < t; i++) { s += "\t"; } return s; } string newLabel(){ labelNum ++ ; string s = "Label_" ; //generate a new label. s += converter.integerToString(labelNum); return s ; } string newTemp(){ tempNum ++ ; string s = "tempVar_" ; //generate a new temporary variable. s += converter.integerToString(tempNum); makeVar(s); return s ; } string newResult( ){ resNum ++; string s = "resVar_" ; s += converter.integerToString(resNum); makeVar(s); return s; } string newResult(string str){ resNum ++; string s = str ; makeVar(s); return s; } void printInitialMain(){ mainTab++ ; string initial = "MAIN PROC\n"; initial += getTabMain(mainTab); initial += "MOV DX, @DATA\n"; initial += getTabMain(mainTab); initial += "MOV DS, DX\n\n"; printMain(initial); } void declareVariable(SymbolInfoNode *node1, const BisonUtil &butil){ printDeb("Inside declareVariable .... node1 = " + node1->getName()); string temp = makeName(node1, butil); node1->symbol = temp; printDeb("\t=>>After code. node1->symbol = " + node1->symbol); string c = node1->symbol + " DW ?"; printDeb("\t\t===>Data must be: " + c); printData(c); } void declareArray(SymbolInfoNode *node1, SymbolInfoNode *node2, const BisonUtil &butil){ printDeb("Inside declareArray .... node1 = " + node1->getName() + " , and node2 = " + node2->getName()); string temp = makeName(node1, butil); node1->symbol = temp ; printDeb("\t=>>After code. node1->symbol = " + node1->symbol); string c = node1->symbol + " DW " + node2->getName() + " DUP(0) "; //? dile problem hoy printDeb("\t\t===>Data must be: " + c); printData(c); } string makeName(SymbolInfoNode *node1, const BisonUtil &butil){ string s = node1->getName() + "_" + converter.integerToString(butil.tab->getCurrentScopeID()); return s; } void printID(SymbolInfoNode *src, SymbolInfoNode *node, string currentFunc){ printDeb("---->>Inside printID .. node->name = " + node->symbol_name + " , and node->symbol = " + node->symbol + " , and currentFunc = " + currentFunc); printDeb("PRINTING For Table node = " + node->getPrintForTable()); string s = "\n\t\t;Printing " + node->symbol_name + "\n"; s += "\tPUSH AX\n"; //For Temporary use things string s2 = "\tMOV AX, " + node->symbol + "\n"; //To enter this number s += s2; s += "\tCALL OUTDEC\n"; //To print that number s += "\tPOP AX\n\t\t;Printing " + node->symbol_name + " is done " + "\n\n"; //To restore AX value src->code = s; //printCode(s, currentFunc); } void printDeb(string s, SymbolInfoNode *n){ printDeb(s + ", <<< Name : " + n->symbol_name + ", symbol : " + n->symbol + ", code : \n" + n->code + ", isArray : " + converter.boolToString(n->isArray) + ", n->dataType = " + n->dataType + " >>>>"); } bool doesNodeExist(SymbolInfoNode *n, const BisonUtil &butil){ SymbolInfoNode *res = butil.tab->LookUp(n->symbol_name); if(res){ return true; }else{ return false; } } void assignOp(SymbolInfoNode *src, SymbolInfoNode *left, SymbolInfoNode *right, const BisonUtil &butil){ /* $$=$1; $$->code=$3->code+$1->code; $$->code+="mov ax, "+$3->getSymbol()+"\n"; if($$->getType()=="notarray"){ $$->code+= "mov "+$1->getSymbol()+", ax\n"; } else{ $$->code+= "mov "+$1->getSymbol()+"[bx], ax\n"; } delete $3; */ printDeb("=================+>>>Before assignOp\nleft = ", left); printDeb("right = ", right); src->setSymbol(left); src->setUnion(" = "); src->setUnion(right); src->symbol = left->symbol ; string code = "\t\t;This is the starting of assignment op. " + left->symbol_name + " = " + right->symbol_name + "\n"; code += (right->code + left->code); code += ("\tMOV AX, " + right->symbol + "\n"); if(src->isArray == false){ code += ("\tMOV " + left->symbol + ", AX\n"); } else{ code += ("\tMOV " + left->symbol + "[BX], AX\n"); } code += "\t\t;Assignment op over " + left->symbol_name + " = " + right->symbol_name; code += "\n\n"; src->code = code ; printDeb("-->>>After assignOp , we are printing the code now .. , src = ", src); //printCode(code, butil); } bool isArray(SymbolInfoNode *n){ //APATOTO RETURN n->isArray return n->isArray ; } void arrayMaking(SymbolInfoNode *src, SymbolInfoNode *arrayName, SymbolInfoNode *exp, const BisonUtil &butil){ //$$->code=$3->code+"mov bx, " +$3->getSymbol() +"\nadd bx, bx\n"; bool flag = false; string temp = ""; src->makeNode(arrayName); string finalCode = ""; finalCode = exp->code + "\n"; finalCode += ("\tMOV BX, " + exp->symbol + "\n"); //finalCode += ("\tADD BX, BX\n"); //Can use SHL BX, 1 finalCode += ("\tSHL BX, 1\n"); if(arrayName){ arrayName->code = finalCode; arrayName->symbol = temp ; //src->symbol = ""; SymbolInfoNode *res = getSymbolFromST(arrayName, butil); if(res){ src->symbol = res->symbol; }else{ src->symbol = arrayName->symbol; } src->code = finalCode; printDeb("=>Line 278 Array Making, For src = " + src->getName() + ", symbol = " + src->symbol + ", code: \n" + src->code); //printCode(finalCode, butil.currentFunctionName); } } void setArraySymbol(SymbolInfoNode *src, SymbolInfoNode *var, const BisonUtil &butil){ /* factor -> variable rule .. char *temp= newTemp(); $$->code+="mov ax, " + $1->getSymbol() + "[bx]\n"; $$->code+= "mov " + string(temp) + ", ax\n"; $$->setSymbol(temp); */ printDeb("==-->>Line 293. Iutil.h, factor ->variable rule .. \nvar =", var); src->makeNode(var); printDeb("->src = ", src); if(var->isArray == true){ string temp = newTemp(); string code = ""; string name = var->symbol_name; code += ("\n\t;This starts array setting " + temp + " has the value of " + var->symbol_name); code += var->code ; var = getSymbolFromST(var, butil); if(!var){ printDeb("var with name : " + var->symbol_name + " does not exist in ST."); return ; } printDeb("==-->>Line 301 arraycheck. Iutil.h, \nvar =", var); code += ("\tMOV AX, " + var->symbol + "[BX]\n"); code += ("\tMOV " + temp + ", AX\n"); code += ("\t;Now " + temp + " has the value of " + name + "\n"); //MY EDIT 6 45 pm Friday //code += ("\tMOV " + temp + ", AX"); src->code = code; src->symbol = temp; //printCode(src->code, butil); } else{ //DO NOTHING IF NOT AN ARRAY! } printDeb("->After (factor -> var ) setting src, src = ", src); } void relAndLogicOp(SymbolInfoNode *src, SymbolInfoNode *lNode, SymbolInfoNode *rNode, SymbolInfoNode *operation, const BisonUtil &butil){ printDeb("\n================================-------=>>Inside Line 264 relAndLogicOp ... "); printDeb("lNode = ", lNode); printDeb("rNode = ", rNode); printDeb("operation = ", operation); printDeb("src = ", src); src->makeNode(lNode); string code = "\n\t\t;This starts the relation op " + operation->symbol_name + " between " + lNode->symbol_name + " and " + rNode->symbol_name + "\n"; code += (lNode->code + rNode->code); if(operation->getName() == "&&"){ //Make And Operation //NEED TO CHECK WITH 1 Of Both sides then make AND string temp1 = newTemp(); string l1 = "\tMOV AX, " + lNode->symbol + "\n"; l1 += ("\tAND AX, " + rNode->symbol + "\n"); l1 += ("\tMOV " + temp1 + ", AX\n"); // string l2 = "\tMOV DX, " + rNode->symbol + "\n"; code += l1; src->symbol = temp1; } else if(operation->getName() == "||"){ //Make Or Operation string temp1 = newTemp(); string l1 = "\tMOV AX, " + lNode->symbol + "\n"; l1 += ("\tOR AX, " + rNode->symbol + "\n"); l1 += ("\tMOV " + temp1 + ", AX\n"); // string l2 = "\tMOV DX, " + rNode->symbol + "\n"; code += l1; src->symbol = temp1; } else{ // / if(operation->getName() == "<"){} string l1 = "\tMOV AX, " + lNode->symbol + "\n"; l1 += ("\tCMP AX, " + rNode->symbol + "\n"); string temp = newTemp(); string label1 = newLabel(); string label2 = newLabel(); string op = ""; src->symbol = temp; l1 += ("\tMOV " + src->symbol + ", 0\n"); //Negative Logic First string opName = operation->getName(); if(opName == "<"){ op = ("\tJL " + label1 + "\n"); } else if(opName == "<="){ op = ("\tJLE " + label1 + "\n"); } //ARO OPERATIONS BAAKI.. else if(opName == ">"){ op = ("\tJG " + label1 + "\n"); } else if(opName == ">="){ op = ("\tJGE " + label1 + "\n"); } else if(opName == "=="){ op = ("\tJE " + label1 + "\n"); } else if(opName == "!="){ op = ("\tJNE " + label1 + "\n"); } l1 += op ; l1 += ("\tJMP " + label2 + "\n"); //Jump to END_IF l1 += (" " + label1 + ": \n"); l1 += ("\tMOV " + src->symbol + ", 1\n"); l1 += (" " + label2 + ": ;this label continues with original code\n"); code += l1; } src->symbol_name = (lNode->symbol_name + " " + operation->symbol_name + " " + rNode->symbol_name); code += ("\t\t; This ends the relation op " + operation->symbol_name + " between " + lNode->symbol_name + " and " + rNode->symbol_name + "\n\n"); src->code = code ; //printCode(code, butil); printDeb("AFTER relAndLogicOp ... printing source = ", src); } string makeVar(string varName, string val, const BisonUtil &butil){ string s = varName ; s += " DW "; s += val; printData(s); return varName; } string makeVar(string varName, const BisonUtil &butil){ return makeVar(varName, "?", butil); } string makeVar(string varName){ string val = "?"; string s = varName ; s += " DW "; s += val; printData(s); return varName; } SymbolInfoNode *addop(SymbolInfoNode *src, SymbolInfoNode *left, SymbolInfoNode *expression, SymbolInfoNode *right, const BisonUtil &butil){ /* $$=$1; $$->code+=$3->code; // move one of the operands to a register, perform addition or subtraction with the other operand and move the result in a temporary variable if($2->getSymbol()=="+"){ } else{ } delete $3; cout << endl; */ src = new SymbolInfoNode(); setSymbol(src, left, (left->symbol_name + expression->symbol_name + right->symbol_name)); string initCode = (left->code + right->code) ; string symbol = newTemp(); src->symbol = symbol ; string code = ""; if(expression->getName() == "+"){ //ADDITION code += ("\n\t;Addition begins between " + left->getName() + " , " + right->getName() + "\n"); // move one of the operands to a register, perform addition or subtraction //with the other operand and move the result in a temporary variable code += ("\tMOV AX, " + left->symbol + "\n"); code += ("\tADD AX, " + right->symbol + "\n"); code += ("\tMOV " + src->symbol + ", AX\n"); code += ("\t;Addition ENDS between " + left->getName() + " , " + right->getName() + "\n"); } else if(expression->getName() == "-"){ //SUBTRACTION code += ("\n\t;Subtraction begins between " + left->getName() + " , " + right->getName() + "\n"); code += ("\tMOV AX, " + left->symbol + "\n"); code += ("\tSUB AX, " + right->symbol + "\n"); code += ("\tMOV " + src->symbol + ", AX\n"); code += ("\t;Subtraction ENDS between " + left->getName() + " , " + right->getName() + "\n"); } string finalCode = initCode + code ; src->code = finalCode; printDeb("\n======================Inside addop printing left, exp, right, src serially.=======================\n"); printDeb("Left: " + left->getPrintForTable() + "\nRight: " + right->getPrintForTable() + "\nexp: " + expression->getName() + "\nSrc: " + src->getPrintForTable()); printDeb("\n==>>>After addop, src = " + src->getPrintForTable() + "\n===================[DONE ADDOP]================================\n"); return src; } SymbolInfoNode* mulop(SymbolInfoNode *src, SymbolInfoNode *left, SymbolInfoNode *expression, SymbolInfoNode *right, const BisonUtil &butil){ /* $$=$1; $$->code += $3->code; $$->code += "mov ax, "+ $1->getSymbol()+"\n"; $$->code += "mov bx, "+ $3->getSymbol() +"\n"; char *temp=newTemp(); if($2->getSymbol()=="*"){ $$->code += "mul bx\n"; $$->code += "mov "+ string(temp) + ", ax\n"; } else if($2->getSymbol()=="/"){ // clear dx, perform 'div bx' and mov ax to temp } else{ // clear dx, perform 'div bx' and mov dx to temp } $$->setSymbol(temp); cout << endl << $$->code << endl; delete $3; } */ src = new SymbolInfoNode(); setSymbol(src, left, (left->symbol_name + expression->symbol_name + right->symbol_name)); string symbol = newTemp(); src->symbol = symbol ; string code_init = (left->code + right->code); string code = "\t;Beginning Mulop " + expression->getName() + " between " + left->symbol_name + " , " + right->symbol_name + "\n"; code += ("\tMOV AX, " + left->symbol + "\n"); code += ("\tMOV BX, " + right->symbol + "\n"); if(expression->getName() == "*"){ //This is multiplication code += ("\tMUL BX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); } else if(expression->getName() == "/"){ //This is division /* code += ("\tXOR DX, DX\n"); //Clear DX code += ("\tDIV BX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); */ //WE do SIGNED Division code += ("\tCWD\n"); code += ("\tIDIV BX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); } else if(expression->getName() == "%"){ //This is modulus /* code += ("\tXOR DX, DX\n"); //Clear DX code += ("\tDIV BX\n"); code += ("\tMOV " + src->symbol + ", DX\n"); */ //Signed Division performed code += ("\tCWD\n"); code += ("\tIDIV BX\n"); code += ("\tMOV " + src->symbol + ", DX\n"); } code += "\t;Ending Mulop " + expression->getName() + " between " + left->symbol_name + " , " + right->symbol_name + "\n"; string finalCode = code_init + code ; src->code = finalCode; printDeb("\n*******************Inside mulop printing left, exp, right, src serially**************n"); printDeb("Left: " + left->getPrintForTable() + "\nRight: " + right->getPrintForTable() + "\nexp: " + expression->getName() + "\nSrc: " + src->getPrintForTable()); printDeb("\n==>>>After addop, src = " + src->getPrintForTable() + "\n****************************DONE mulop****************************n"); return src; } SymbolInfoNode* unary(SymbolInfoNode *src, SymbolInfoNode *expression, SymbolInfoNode *left){ /* NOT $$=$2; char *temp=newTemp(); $$->code="mov ax, " + $2->getSymbol() + "\n"; $$->code+="not ax\n"; $$->code+="mov "+string(temp)+", ax"; */ src = new SymbolInfoNode(); setSymbol(src, left, (expression->symbol_name + left->symbol_name)); /* string symbol = newTemp(); src->symbol = symbol ; */ string op = expression->getName(); if(op == "!"){ //NOT OPERATION string symbol = newTemp(); src->symbol = symbol ; string code = left->code; code += ("\t\t\t;NOT OPERATION starts for " + left->getName() + "\n"); string label1 = newLabel(); string label2 = newLabel(); /*code += ("\tMOV AX, " + left->symbol + "\n"); code += ("\tNOT AX\n"); code += ("\tMOV " + src->symbol + ", AX\n");*/ code += indent("MOV AX, " + left->symbol); code += indent("CMP AX, 0"); code += indent("JE " + label1); code += indent("MOV AX, 0"); code += indent("JMP " + label2); code += (label1 + ":\n"); code += indent("MOV AX, 1"); code += (label2 + ":\n"); code += indent("MOV " + src->symbol + ", AX"); code += ("\t\t\t;NOT OPERATION ENDS for " + left->getName() + "\n"); src->code = code ; } else if(op == "-"){ //NEG OPERATION string symbol = newTemp(); src->symbol = symbol ; string code = left->code; code += ("\t\t\t;NEG OPERATION starts for " + left->getName() + "\n"); code += ("\tMOV AX, " + left->symbol + "\n"); code += ("\tNEG AX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); code += ("\t\t\t;NEG OPERATION ENDS for " + left->getName() + "\n"); src->code = code ; } printDeb("\n*******************Inside mulop printing left, exp, right, src serially**************n"); printDeb("Left: " + left->getPrintForTable() + "\nexp: " + expression->getName() + "\nSrc: " + src->getPrintForTable()); printDeb("\n==>>>After addop, src = " + src->getPrintForTable() + "\n****************************DONE mulop****************************n"); return src; } SymbolInfoNode *if_op(SymbolInfoNode *src, SymbolInfoNode *expression, SymbolInfoNode *statement){ /* $$=$3; char *label=newLabel(); $$->code+="mov ax, "+$3->getSymbol()+"\n"; $$->code+="cmp ax, 0\n"; $$->code+="je "+string(label)+"\n"; $$->code+=$5->code; $$->code+=string(label)+":\n"; */ //dol_3 is expression src = new SymbolInfoNode(); setSymbol(src, expression, ("if(" + expression->getName() + ")\n" + statement->getName())); src->symbol = "IF_SYMBOL"; string code = expression->code ; string label = newLabel(); code += ("\t\t; IF starts ( " + expression->getName() + ")\n"); code += ("\tMOV AX, " + expression->symbol + "\n"); code += ("\tCMP AX, 0\n"); code += ("\tJE " + label + "\n"); code += statement->code ; code += (label + ":\n"); src->code = code ; printDeb("\n======++>>>=======Inside if printing exp, statement, src <<<<<<<<===========n"); printDeb("exp: " + expression->getPrintForTable() + "\n"); printDeb("statement: " + statement->getPrintForTable()); printDeb("\n==>>>After op, src = " + src->getPrintForTable() + "\n=============++>>>>>> DONE if<<===========================n"); return src; } SymbolInfoNode *ifElse_op(SymbolInfoNode *src, SymbolInfoNode *expression, SymbolInfoNode *ifStatement, SymbolInfoNode *elseStatement){ /* $$=$3; char *label=newLabel(); $$->code+="mov ax, "+$3->getSymbol()+"\n"; $$->code+="cmp ax, 0\n"; $$->code+="je "+string(label)+"\n"; $$->code+=$5->code; $$->code+=string(label)+":\n"; */ src = new SymbolInfoNode(); setSymbol(src, expression, ("if(" + expression->getName() + ")\n" + ifStatement->getName() + "else\n" + elseStatement->getName())); src->symbol = "IF_ELSE_SYMBOL"; string comp = "if(" + expression->getName() + ")" ; string code = expression->code ; string else_label = newLabel(); string end_label = newLabel(); code += ("\t\t; IF_ELSE starts ( " + expression->getName() + ")\n"); code += ("\tMOV AX, " + expression->symbol + "\n"); code += ("\tCMP AX, 0\n"); code += ("\tJE " + else_label + "\n"); code += ifStatement->code ; code += ("\tJMP " + end_label + "\n"); code += (else_label + ":\t; This is the else label \n"); code += elseStatement->code; code += (end_label + ":\t;This is the END_IF Label for the " + comp + " \n"); src->code = code ; printDeb("\n======++>>>=======Inside else if printing src <<<<<<<<===========n"); printDeb("\n==>>>After op, src = " + src->getPrintForTable() + "\n=============++>>>>>> DONE else if<<===========================n"); return src; } SymbolInfoNode *incOrdec(SymbolInfoNode *src, SymbolInfoNode *var, SymbolInfoNode* operation){ src = new SymbolInfoNode(); string name = var->getName() + operation->getName(); setSymbol(src, var, name); //string temp = newTemp(); src->symbol = var->symbol; string code = var->code ; printDeb("\n====>>>>Inside incOrdec .. printing var : " + var->getPrintForTable() + ", op : " + operation->getName()); string op = operation->getName(); if(op == "++"){ code += ("\tINC " + src->symbol + "\n"); } else if(op == "--"){ code += ("\tDEC " + src->symbol + "\n"); } src->code = code ; return src ; } SymbolInfoNode *ForLoop(SymbolInfoNode *src, SymbolInfoNode *initial, SymbolInfoNode *middle, SymbolInfoNode *final, SymbolInfoNode *statement){ src = new SymbolInfoNode(); string name = "for(" + initial->getName() + middle->getName() + final->getName() + ")\n" + statement->getName(); setSymbol(src, initial, name); //$$->setSymbol($1);$$->setUnion($2);$$->setUnion($3);$$->setUnion($4);$$->setUnion($5);$$->setUnion($6); //$$->setUnion("\n"); $$->setUnion($7); /* $$ -> FOR LPAREN expression_statement expression_statement expression RPAREN statement $3 $4 $5 $7 initial middle final statement $3's code at first, which is already done by assigning $$ = $3 create two labels and append one of them in $$->code compare $4's symbol with 0 if equal jump to 2nd label append $7's code append $5's code append the second label in the code */ printDeb("=========================== <<<< FOR LOOP STARTS !! >>> ==========================="); printDeb("initialization : " + initial->getPrintForTable()); printDeb("condition: " + middle->getPrintForTable()); printDeb("increment/decrement: " + final->getPrintForTable()); printDeb("statements : " + statement->getPrintForTable()); string loop_label = newLabel(); string end_label = newLabel(); string code = "\t\t;For loop starts ... for(" + initial->getName() + middle->getName() + final->getName() + ")\n"; code += initial->code ; //code += ("\tMOV AX, " + initial->symbol + "\n"); code += (loop_label + ":\t\t;First Label of the for loop\n"); code += middle->code ; code += ("\t\t;Checking The conditions in loop " + middle->getName() + "\n"); code += ("\tMOV AX, " + middle->symbol + "\n"); code += ("\tCMP AX, 0\n"); code += ("\tJE " + end_label); code += ("\t\t;Writing the statements of for loop now ..\n"); code += (statement->code); code += ("\t\t;Writing the final conditions i.e. increment/decrement..\n"); code += (final->code); code += ("\tJMP " + loop_label + "\n"); code += (end_label + ":\t\t;This is the end loop label .\n"); src->symbol = "FOR_LOOP"; src->code = code ; printDeb("Before exit. src: " + src->getPrintForTable()); printDeb("\n=========================== <<<< DONE WITH FOR LOOP >>> ===========================\n"); return src ; } SymbolInfoNode *whileLoop(SymbolInfoNode *src, SymbolInfoNode *exp, SymbolInfoNode *statement){ //$$->setSymbol($1);$$->setUnion($2);$$->setUnion($3);$$->setUnion($4);$$->setUnion("\n");$$->setUnion($5); //WHILE LPAREN expression RPAREN statement src = new SymbolInfoNode(); string name = "while(" + exp->getName() + ")\n" + statement->getName(); setSymbol(src, exp, name); string loop_label = newLabel(); string end_label = newLabel(); string code = "\t\t;WHILE LOOP STARTS .. while(" + exp->getName() + ")\n"; code += (loop_label + ":\t\t;This is Loop Label\n"); code += exp->code ; code += ("\tMOV AX, " + exp->symbol + "\n"); code += ("\tCMP AX, 0\n"); code += ("\tJE " + end_label + "\n"); code += (statement->code); code += ("\tJMP " + loop_label + "\n"); code += (end_label + ":\t\t;This is end label\n"); //code += statement->code ; //code += ("\t\tThe above is to make sure while lop runs perfect number of times.\n"); code += ("\t\t\t;While Loop Over.\n\n"); src->symbol = "WHILE_LOOP"; src->code = code ; return src; } SymbolInfoNode* defineFunc(SymbolInfoNode *src, string funcName, SymbolInfoNode *statements, const BisonUtil &butil, int currentScope ){ src = new SymbolInfoNode(); setSymbol(src, new SymbolInfoNode(funcName, "ID")); string code = ""; string initial = ""; if(funcName == "main"){ initial += "MAIN PROC\n"; initial += "\tMOV DX, @DATA\n"; initial += "\tMOV DS, DX\n\n"; code += initial; } else{ code += ( "\n" + funcName + " PROC"); } printDeb("\n=======================+++ <<<< FUNCTION DEFINITION >>>> ==========================\n"); printDeb("function name : " + funcName); printDeb("statements is : " + statements->getPrintForTable()); string str = "Paramater list is : size = " + converter.integerToString((int)butil.currentFunctionList.size())+ " \n"; int size = (int)butil.currentFunctionList.size(); for(int i=0; i<size; i++){ str += (butil.currentFunctionList[i]->getPrintForTable()); str += "\n"; } printDeb(str); // string code = indent(statements); if(funcName != "main"){ //Setting the parameters now code += ("\n\t\t;Setting parameters from stack By popping in reverse order\n"); string funcRes = "res_" + funcName; code += ("\tPOP " + funcRes + "\t\t;To pop initial stack item into resultVariable first\n"); for(int i=(int)butil.currentFunctionList.size()-1; i>=0; i--){ string symb = butil.currentFunctionList[i]->symbol ; code += ("\tPOP " + symb + "\n"); } //Setting parameters done from stack.. code += ("\tPUSH " + funcRes + "\t\t;To push the initial stack item back into stack\n"); code += indent(getRegisterPush()); } string statement_indent = (statements->code); code += statement_indent; if((funcName != "main")){ //move the result i.e. content of AX back to the result var associated with this function.. string resultVar = getResult(funcName); if((butil.currentFunctionReturnType == "void") || (butil.currentFunctionReturnType == "VOID")){ //Do nothing code += indent(getRegisterPop()); code += ("\tRET\n"); code += (funcName + " ENDP\n\n"); }else{ //code += ("\n\tMOV " + resultVar + ", AX\t\t;Store result back to the res var of the function " + funcName + "\n"); code += (funcName + " ENDP\n\n"); } } else{ code += ("\n\t\t;Return DOS Control\n"); code += ("\tMOV AH, 4CH\n\tINT 21H\nMAIN ENDP\n\n"); //code += ("\nMAIN ENDP\nJMP LABEL_END\t\t;Jump to END MAIN line \n"); } src->code = code; //Change parameters' symbols SymbolInfoNode *functionSrc = butil.tab->LookUp(funcName); if(functionSrc){ for(int i=0; i<(int)functionSrc->functionItems.list.size(); i++){ functionSrc->functionItems.list[i].symbol = butil.currentFunctionList[i]->symbol; } } printDeb("AFTER changing parameters ... printing those parameters for the funciton ... "); if(functionSrc){ string x = functionSrc->getEverything_3(); printDeb(x); }else{ printDeb("Function Name with name: " + funcName + " DOES not exist in ST yet!"); } printDeb("\n=======================+++ <<<< FUNCTION DEFINITION over >>>> ==========================\n"); return src ; } void pushParameters( const BisonUtil &butil){ if(butil.currentFunctionName == "main"){ //DO NOTHING } else{ int size = (int)butil.currentFunctionList.size(); for(int i=0; i<size; i++){ string name = butil.currentFunctionList[i]->getName(); SymbolInfoNode *res = butil.tab->searchCurrent(butil.currentFunctionList[i]); //name += ("_" + converter.integerToString(butil.tab->getCurrentScopeID())); name += ("_" + butil.currentFunctionName); makeVar(name); if(res){ printDeb("============|]]]]]]]]]]]]]] FOUND in ST parameter ... changin symbol "); res->symbol = name; } butil.currentFunctionList[i]->symbol = name; } printDeb("=======================================>>>>>>>>>>>>>>>>>AFTER CHANGING parameterss .. printin them"); for(int i=0; i<size; i++){ string s = butil.currentFunctionList[i]->getPrintForTable(); printDeb(s + "\n"); } string funName = butil.currentFunctionName ; string resName = newResult("res_" + funName); FunResult fr(funName, resName); this->funResults.push_back(fr); } } SymbolInfoNode *returnFun(SymbolInfoNode *src, SymbolInfoNode *exp, const BisonUtil &butil){ //$$->setSymbol($1); $$->setUnion(" ") ;$$->setUnion($2);$$->setUnion($3); src = new SymbolInfoNode(); string funName = butil.currentFunctionName; string name = "return " + exp->getName() + ";"; src->symbol_name = name ; string code = exp->code ; code += ("\tMOV AX, " + exp->symbol + "\t;Store result temporarily in AX\n"); if(butil.currentFunctionName != "main"){ string resultVar = "res_" + butil.currentFunctionName; string funcName = butil.currentFunctionName; code += ("\n\tMOV " + resultVar + ", AX\t\t;Store result back to the res var of the function " + funcName + "\n"); code += indent(getRegisterPop()); code += ("\tRET\n"); } src->code = code ; return src ; } SymbolInfoNode *funcCall(SymbolInfoNode *src, SymbolInfoNode *func,SymbolInfoNode *args ,const BisonUtil &butil){ src = new SymbolInfoNode(); int line = func->getLineBegin(); func = butil.tab->LookUp(func->getName()); if(!func){ return 0; } setSymbol(src, func); src->symbol_name = (func->getName() + "(" + args->getName() + ")"); src->setLineBegin(line); string str = ""; str += ("===========================+++<<<< INSIDE functionCAll >>>=================================\n"); str += ("func: " + func->getPrintForTable()); str += ("Printing its parameters ..size = " + converter.integerToString(func->functionItems.list.size()) + "\n"); for(int i=0; i<(int)func->functionItems.list.size(); i++){ Variable var = func->functionItems.list[i]; str += var.getVariable(); str += "\n"; } str += ("Now printing arguments... , size = " + converter.integerToString((int)butil.currentArgumentList.listArguments.size()) + "\n"); for(int i=0; i<(int)butil.currentArgumentList.listArguments.size(); i++){ Variable var = butil.currentArgumentList.listArguments[i]; str += var.getVariable(); str += "\n"; } bool isRecursion = false ; string code = "\n\t\t;STARTING function call " + func->getName() + "\n"; //Check for recursion begin if(func->getName() == butil.currentFunctionName){ isRecursion = true; } if(isRecursion == true){ code += ("\n\t\t;Recursion has occurred need to push local variables and parameters into stack\n"); for(int i=0; i<(int)declaredVariables.size(); i++){ //code += ("\t\t;Name[" + converter.integerToString(i) + "] : " + declaredVariables[i]->getName()); //code += (" and symbol is " + declaredVariables[i]->symbol + "\n"); code += getCode(declaredVariables[i], "PUSH"); } code += indent("\t;Local variables pushing is done"); code += indent("\n\t;Now we push paramters into stack .. "); for(int i=0; i<(int)butil.currentFunctionList.size(); i++){ code += getCode(butil.currentFunctionList[i], "PUSH"); } code += indent("\t;Parameter push is over and Recursion handling is done"); } //Check for recursion done code += ("\t\t;Setting args .. number of args = " + converter.integerToString(butil.currentArgumentList.listArguments.size()) + "\n"); printDeb("==========++>>>>>>>>>>>>>>>>===============+>>>>>> CHECKING Code of args ... "); string c = ""; for(int i=0; i<(int)butil.currentArgumentList.listArguments.size(); i++){ c += butil.currentArgumentList.listArguments[i].code ; //4 am Thursday ADDED printDeb("CHECK CODE FOR name: " + butil.currentArgumentList.listArguments[i].name + ", symbol: " + butil.currentArgumentList.listArguments[i].symbol + ", code :\n" + butil.currentArgumentList.listArguments[i].code + "\nDONE\n"); c += "\n\tMOV AX, " + butil.currentArgumentList.listArguments[i].symbol + "\n"; //c += ("\tMOV " + func->functionItems.list[i].symbol + ", AX\n"); c += ("\tPUSH AX\t\t;Push the argument " + butil.currentArgumentList.listArguments[i].name + " in stack\n"); } code += c; code += ("\t\t;Paramater setting with arguments is done, now we call the function .. \n"); code += ("\tCALL " + func->getName() + "\n"); if(isRecursion == true){ code += indent("\t;Now we pop parameters but in reverse order."); for(int i=(int)butil.currentFunctionList.size()-1; i>=0; i--){ code += getCode(butil.currentFunctionList[i], "POP"); } code += ("\t\t;Popping is done for parameters\n"); code += indent("\t;Now pop local variables in reverse order."); for(int i=(int)declaredVariables.size()-1; i>=0; i--){ code += getCode(declaredVariables[i], "POP"); } code += ("\t\t;Popping is over for local variables in reverse order ..\n"); code += indent("\t\t;Popping is done for recursion.\n"); } src->symbol = func->symbol ; src->code = code ; printDeb("========++>>>>>>>>>>src->symbol = " + src->symbol); str += ("=================================++[[[ DONE functionCAll ]]]================================\n"); printDeb(str); return src; } string getCode(SymbolInfoNode *node, string op){ printDeb("==========>>>Inside getCode for name : " + node->getPrintForTable() + ", symbol is " + node->symbol + "\ncode is " + node->code); if(node->isArray == false){ return ("\t" + op + " " + node->symbol + "\n"); } //This is for array int sX = node->arrayItems.size - 1; string sizeArray = converter.integerToString(sX); string loop_label = newLabel(); string end_label = newLabel(); string str = "\t\t;This is array of name : " + node->getName() + " and size : " + converter.integerToString(node->arrayItems.size) + "\n"; str += indent("MOV primary_variable, CX\t\t;To store the current value of CX"); str += indent("XOR CX, CX\t\t;CX is the counter variable = 0"); if(op == "PUSH"){ str += indent("XOR SI, SI\t\t;Initialize SI as 0"); }else{ int final = 2*(node->arrayItems.size) - 2; str += indent("MOV SI, " + converter.integerToString(final) + "\t\t;Initialize SI as size*2 - 2"); } str += (loop_label + ":\n"); if(op == "PUSH"){ str += indent("MOV AX, " + node->symbol + "[SI]"); str += indent(op + " AX"); }else{ str += indent(op + " AX"); str += indent("MOV " + node->symbol + "[SI], AX"); } str += indent("CMP CX, " + sizeArray); str += indent("JGE " + end_label); if(op == "PUSH"){ str += indent("ADD SI, 2"); }else{ str += indent("SUB SI, 2"); } str += indent("INC CX"); str += indent("JMP " + loop_label); str += (end_label + ":\n\tMOV CX, primary_variable\t\t;To restore original value of CX\n"); str += indent("\t\t;Array " + op + " into stack is done"); return str ; } void declareFunction(string funcName, const BisonUtil &butil){ string result = converter.makeName("res", funcName); makeVar(result); SymbolInfoNode *res = butil.tab->LookUp(funcName); if(res){ res->symbol = converter.makeName("res", funcName); } } void declareFunction(string funcName, string paramName, const BisonUtil &butil){ printDeb("=================================****Inside declareFunction[2]****===================================="); printDeb("Function name: " + funcName); printDeb("Parameter name: " + paramName); int size = (int)butil.currentFunctionList.size(); printDeb("Printing parameters from butil... , size.param = " + converter.integerToString(size)); for(int i=0; i<size; i++){ string s = butil.currentFunctionList[i]->getPrintForTable(); string name = butil.currentFunctionList[i]->getName(); string var = converter.makeName(name, funcName); printDeb("Name: " + name + ", var name: " + var); makeVar(var); } string result = converter.makeName("res", funcName); printDeb("Result variable name: " + result); makeVar(result); printDeb("Getting from ST and setting the symbols accordingly.."); SymbolInfoNode *res = butil.tab->LookUp(funcName); if(res){ printDeb("Result found in ST !!, res->isFunction = " + converter.boolToString(res->isFunction)); int size = res->functionItems.list.size(); printDeb("Printing parameters ... size = " + converter.integerToString(size)); for(int i=0; i<size; i++){ string name = res->functionItems.list[i].name ; string varName = converter.makeName(name, funcName); res->functionItems.list[i].symbol = varName; Variable var = res->functionItems.list[i]; string s = var.getVariable(); printDeb(s); res->symbol = converter.makeName("res", funcName); } }else{ printDeb("RESULT not found in ST!!"); } printDeb("=================================****Ending declareFunction[2]****===================================="); } void removeDeclaredVariables(){ int size = (int)declaredVariables.size(); if(size != 0){ declaredVariables.clear(); } } void pushDeclaredVariables(SymbolInfoNode *node){ SymbolInfoNode *newNode = new SymbolInfoNode(); printDeb("===>>>Inside pushDeclaredVariables .. node is " + node->getPrintForTable()); newNode->makeNode(node); declaredVariables.push_back(newNode); } string getResult(string fun){ for(int i=0; i<(int)funResults.size(); i++){ FunResult fr = funResults[i]; if(fr.funName == fun){ return fr.resName; } } return "NO_RESULT"; } string indent(string s){ vector<string> line = converter.splitString(s, '\n'); string res = ""; if(line.size() == 0){ return ("\t" + s + "\n"); } for(int i=0; i<(int)line.size(); i++){ string str = line[i]; string s1 = "\t" + str + "\n"; res += s1; } return res; } string getRegisterPop(){ string s = "\n\t\t;POP ALL REGS begin"; s += ("\nPOP DX\nPOP CX\nPOP BX\nPOP AX\n"); s += ("\t\t;POP ALL REGS ends\n\n"); return s ; } string getRegisterPush(){ string s = ""; s += ("\n\t\t;PUSH ALL REGS begin"); s += ("\nPUSH AX\nPUSH BX\nPUSH CX\nPUSH DX\n"); s += ("\t\t;PUSH ALL REGS end\n\n"); return s ; } void setSymbol(SymbolInfoNode *n, SymbolInfoNode *node, string name){ if(!n){ n = new SymbolInfoNode(); } //n->symbol_name = node->getName(); n->symbol_type = node->getType(); n->dataType = node->dataType; n->setLineBegin(node->getLineBegin()); n->isArray = node->isArray; n->isFunction = node->isFunction; n->code = node->code ; n->symbol = node->symbol; if(n->isArray){ n->arrayItems.changeArray(node->arrayItems); } if(n->isFunction){ n->functionItems.changeFunction(node->functionItems); } n->setLineBegin(node->getLineBegin()); n->next = 0 ; n->symbol_name = name; //printDeb("-------------------___>>>>>After setSymbol.. printing src = " + n->getPrintForTable()); } void setSymbol(SymbolInfoNode *n, SymbolInfoNode *node){ setSymbol(n, node, node->getName()); } void printFullCode(SymbolInfoNode *node, const BisonUtil &butil){ printCode(node->code , butil); } void printCode(string code, const BisonUtil &butil){ if(butil.currentFunctionName == "main"){ printMain(code); }else{ printMain(code); } } void printCode(string code, string currentFunc){ if(currentFunc == "main"){ printMain(code); }else{ printMain(code); } } SymbolInfoNode *getSymbolFromST(SymbolInfoNode *node, const BisonUtil &butil){ string name = getArrayName(node->getName()); SymbolInfoNode *res = butil.tab->LookUp(name); return res; } string getArrayName(string arr){ string lName = ""; for(int i=0; i<arr.length(); i++){ if(arr[i] == '['){ break; }else{ lName += arr[i]; } } return lName; } void printFinalCode(){ string initial = ".MODEL SMALL\n.STACK 100H\n"; codeOut << initial << endl ; //PRINTING DATA SEGMENT !! //Printing from set. //printDeb("==============+*Printing dataSet*+================ size = " + converter.integerToString(dataSet.size())); codeOut << ".DATA\n"; for(set<string>::iterator it = dataSet.begin(); it != dataSet.end(); it ++){ string line = *it ; //printDeb(line + "\n"); codeOut << line << endl ; } codeOut << "\n"; //PRINTING CODE SEGMENT !! codeOut << ".CODE" << endl << endl ; //Other Functions for(int i=0; i<(int)otherFunctions.size(); i++){ codeOut << otherFunctions[i] << endl ; } //Main Function for(int i=0; i<(int)mainLines.size(); i++){ codeOut << mainLines[i] << endl; } //codeOut << "\nMAIN ENDP\nEND MAIN\n\n"; } }; /* if(op == "++"){ code += ("\t\t;INCOP of variable " + var->getName() + "begins.\n"); code += ("\tMOV AX, " + var->symbol + "\n"); code += ("\tINC AX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); code += ("\t\t;INCOP ends of " + var->getName() + "\n"); } else if(op == "--"){ code += ("\t\t;DECOP of variable " + var->getName() + "begins.\n"); code += ("\tMOV AX, " + var->symbol + "\n"); code += ("\tDEC AX\n"); code += ("\tMOV " + src->symbol + ", AX\n"); code += ("\t\t;DECOP ends of " + var->getName() + "\n"); } */ /*string getSymbolFromFunction(SymbolInfoNode *idName, const BisonUtil &butil){ string s = ""; string id = idName->getName(); SymbolInfoNode *res = butil.tab->searchCurrent(idName); if(res){ //Is already defined in this function ... }else{ //Not defined in this function ... int size = (int)butil.currentFunctionList.size(); for(int i=0; i<size; i++){ if(butil.currentFunctionList[i]->getName() == id){ //Match found with parameter.... return butil.currentFunctionList[i]->symbol; } } } return s; }*/ // /DOESNOT WORK <file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include <streambuf> #include <set> #include "Optimizer.h" //#include "IntermediateCodeStuffs/Optimizer.h" using namespace std ; int main(){ Optimizer opt ; opt.optimize(); printf("\n\n<<--DONE INSIDE OptimizerRunner.cpp-->>\n\n"); }<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include "1505022_BisonUtil.h" #include "../Miscalenous/Converter.h" #define DODO "DODO" #define DUMMY "dumVal" using namespace std ; class SemanticUtil{ public : Converter converter; bool checkFloatFlag ; string errorVoid = "NOTHING ASSIGNED YET!!" ; void printSemantic(string s, BisonUtil butil) { butil.printSemantic(s); } string getString(int x){ return converter.integerToString(x); } string getString(float x){ return converter.floatToString(x); } void printSemantic(string str, const BisonUtil &butil, SymbolInfoNode *node1, SymbolInfoNode *node2){ string s = ""; s += "\n=======================<< In printSemantic function >>============================\n"; s += str ; s += "\n"; s += node1->getPrintForTable(); s += "\n"; s += node2->getPrintForTable(); s += "\n===================== << DONE >> =================================\n"; butil.printSemantic(s); } void printSemantic(SymbolInfoNode *node, const BisonUtil &butil){ string s = ""; s += "\n=======================<< In printSemantic function >>============================\n"; s += node->getPrintForTable(); s += "\n===================== << DONE >> =================================\n"; butil.printSemantic(s); } void checkAndChangeInSymbolTable(SymbolInfoNode *node1, const BisonUtil &butil){ string s ; butil.printSemantic("Line 53 done."); SymbolInfoNode *res = butil.searchForUndeclaredID(node1); butil.printSemantic("Line 57 done."); if(res){ node1->makeNode(res); } else{ s = "At Line. " ; s += butil.getString(node1->getLineBegin()); s += " , variable undeclared."; s += " variable name is " ; s += node1->getName(); butil.printError(s); } } string getNameOfType(string type){ if(type == "INT"){ return "int"; } if(type == "FLOAT") return "float"; if(type == "VOID") return "void"; return "NIL"; } string integerTrimmed(string s){ float x = converter.stringToFloat(s); int z = (int)x; return converter.integerToString(z); } bool isValidNameOfID(string id, const BisonUtil &butil){ butil.printSemantic("\n??????????=>>>>>> Inside isValidNameOfID(..) .. printing id = " + id); int len = id.length(); for(int i=0; i<len; i++){ if((id[i] == '{') ||(id[i] == '}') ||(id[i] == '(') ||(id[i] == ')') ||(id[i] == '[') ||(id[i] == ']') ||(id[i] == '+') ||(id[i] == '-')||(id[i] == '/')||(id[i] == '?')||(id[i] == '<')||(id[i] == '>')||(id[i] == '=')){ return false; } } char charArr[11] = {'0','1','2','3','4','5','6','7','8','9'}; for(int i=0; i<11; i++){ if(id[0] == charArr[i]) return false; } butil.printSemantic("RETURNING true.\n"); return true ; } void assignOpArray(SymbolInfoNode *src, SymbolInfoNode *lhs, SymbolInfoNode *rhs, const BisonUtil &butil){ string lName = lhs->getName(); string name = ""; for(int i=0; i<lName.length(); i++){ if(lName[i] == '[') break ; name += lName[i]; } SymbolInfoNode *checkNode = new SymbolInfoNode(name, lhs->getType(), lhs->getLineBegin(), lhs->dataType); checkNode->isArray = lhs->isArray; checkNode->isFunction = lhs->isFunction; checkNode->actualValue = lhs->actualValue; SymbolInfoNode *res = checkDeclaredIDArray(checkNode, butil, false); SymbolInfoNode *l ; if(res){ l = res ; butil.printSemantic("FOUND res.. printing res =" + res->getPrintForTable()); }else{ l = lhs ; butil.printSemantic("RES DOESNOT EXIST HERE..."); } string s = "++==----++==--->>> Inside assignOpArray ... printing lhs(res), rhs\n"; s += l->getPrintForTable(); s += "\n"; s += rhs->getPrintForTable(); s += "\n"; butil.printSemantic(s); if(res && rhs) butil.printSemantic("===========+>>>>>> Line 137 sutil. res->dataType = " + res->dataType + " , and rhs->dataType = " + rhs->dataType); if(res){ if(res->dataType == "INT"){ if(rhs->dataType == "FLOAT"){ butil.printError("SEMANTIC WARNING at line. " + converter.integerToString(lhs->getLineBegin()) + ", Trying to assign float with int array."); } } else{ if(checkFloatFlag == true){ if(res->dataType == "FLOAT"){ if(rhs->dataType == "INT"){ butil.printError("SEMANTIC WARNING, at line. " + converter.integerToString(lhs->getLineBegin()) + ", Trying to assign int with float array."); } } } } } s += "\nFINALLY PRINTING src=" ; //DO THING FOR SOURCE AND PUSH IN VECTOR's INDEX... //,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,<<NNNNNEEEED TO EDIIT HEREEE >>>>> ////////////////////////////// s += src->getPrintForTable(); s += "\n<<<<<<<<<<<<<< DONE assignOpArray DONE >>>>>>>>>>>>>>>\n"; butil.printSemantic(s); } void assignRightArray(SymbolInfoNode *src, SymbolInfoNode *lhs, SymbolInfoNode *rhs, const BisonUtil &butil) { string s = "\n\n===>>> Inside ==>> assignRightArray(...) \n"; s += "Printing lhs, rhs\n lhs: "; s += lhs->getPrintForTable(); s += "\nrhs: "; s += rhs->getPrintForTable(); s += "\n<<<< DONE assignRightArray ... >>>> \n\n"; butil.printArrayDebug(s); lhs = butil.tab->LookUp(lhs->getName()); string lType, rType; if(lhs){ if(rhs){ if(rhs->isArray){ lType = lhs->dataType; rType = rhs->dataType; if((lType == "INT") && (rType == "FLOAT")){ butil.printError("SEMANTIC WARNING at line. " + converter.integerToString(rhs->getLineBegin()) + ", trying to assign a float to an integer."); }else{ if(this->checkFloatFlag == true){ if((lType == "FLOAT") && (rType == "INT")){ butil.printError("SEMANTIC WARNING at line. " + converter.integerToString(rhs->getLineBegin()) + ", trying to assign an integer to a float."); } } } } } } } //>>>>>>>>>>>>>>>>NEED TO CHANGE HERE<<<<<<<<<<<<<<<<<< KISU EKTA BHUL HOISE ((4 * 3 ) == (3 * 4)) <NAME> NA void assignOp(SymbolInfoNode *src, SymbolInfoNode *lhs, SymbolInfoNode *rhs, const BisonUtil &butil) { //src is $$, lhs is $1, ASSIGNOP is $2 and rhs is $3 string lhsType = lhs->dataType; string rhsType = rhs->dataType; string lType = getNameOfType(lhsType); string rType = getNameOfType(rhsType); lhs->actualValue = rhs->actualValue; src->actualValue = lhs->actualValue; string strToPrint = "???????????? ========+>>>> INSIDE assignOp() <<<<<<<<===============\n"; strToPrint += "lhs =" ; strToPrint += lhs->getPrintForTable(); strToPrint += "\nrhs ="; strToPrint += rhs->getPrintForTable(); strToPrint += "?>?>?>?><?><?><?><?><?> DONE assignOp ><><>?>??????\n"; butil.printArrayDebug(strToPrint); butil.printSemantic(strToPrint); string lName = lhs->getName(); bool isThisArray = false; for(int i=0; i<lName.length(); i++){ if(lName[i] == '['){ isThisArray = true; } } if(isThisArray == true){ assignOpArray(src, lhs, rhs, butil); return ; } //printf("2nd BLA BLA BLA BLA\n\n"); bool flag = isValidNameOfID(lName, butil); if(lType == "NIL") return; if(rType == "NIL") return ; if((lhsType == "INT") && (rhsType == "FLOAT")){ butil.printError("SEMANTIC WARNING at line. " + butil.getString(rhs->getLineBegin()) + " , Trying to assign " + lType + " with " + rType); return ; lhs->actualValue = integerTrimmed(rhs->actualValue); } else if((lhsType == "FLOAT") && (rhsType == "INT")){ if(checkFloatFlag){ butil.printError("SEMANTIC WARNING, at line. " + butil.getString(rhs->getLineBegin()) + " , Trying to assign " + lType + " with " + rType); } return ; lhs->actualValue = rhs->actualValue ; } else{ lhs->actualValue = rhs->actualValue; } src->actualValue = lhs->actualValue; src->dataType = lhsType; SymbolInfoNode *res ; if(flag == true){ res = butil.tab->LookUp(lhs->getName()); //res->makeNode(lhs); string str = "========+>>>>>>INSIDE ASSIGNOP .. printing src, lhs, rhs, res \n"; str += src->getPrintForTable(); str += "\n"; str += lhs->getPrintForTable(); str += "\n"; str += rhs->getPrintForTable(); str += "\n"; str += res->getPrintForTable(); str += "\n??????????? <<<<<<<<<<< DONE >>>>>>>>>>>>>>>> ????????????????\n"; butil.printSemantic(str); } else{ //DO NOTHING... string str = "========+>>>>>>INSIDE ASSIGNOP .. printing src, lhs, rhs, res is null \n"; str += src->getPrintForTable(); str += "\n"; str += lhs->getPrintForTable(); str += "\n"; str += rhs->getPrintForTable(); str += "\n"; str += "\n??????????? <<<<<<<<<<< DONE >>>>>>>>>>>>>>>> ????????????????\n"; butil.printSemantic(str); } string s = "After ASSIGNOP of " + lhs->getName() + " with " + rhs->getName() + " , and printing table.\n" ; s += butil.tab->printCurrentNonEmpty(); butil.printSemantic(s); //butil.printArrayDebug(s); //$$->setSymbol($1); $$->setUnion(" ") ; $$->setUnion($2); $$->setUnion(" ") ;$$->setUnion($3); } void assignRightArrayWithArray(SymbolInfoNode *src, SymbolInfoNode *lhs, SymbolInfoNode *rhs, const BisonUtil &butil){ } SymbolInfoNode *findFromST(SymbolInfoNode *node, const BisonUtil &butil){ butil.printSemantic("--->>>Inside findFromST, printing node=" , node); string name = node->getName(); SymbolInfoNode *res = butil.searchForUndeclaredID(node); //EDITED HERE FOR CHECKING LINE NUMBERS THIKASE NAKI NA!. //res->setLineBegin(node->getLineBegin()); return res; } void checkType(SymbolInfoNode *lhs, SymbolInfoNode *rhs, const BisonUtil &butil){ string lType = getNameOfType(lhs->dataType); string rType = getNameOfType(rhs->dataType); if(lType != rType){ butil.printError("SEMANTIC WARNING at line. " + butil.getString(lhs->getLineBegin()) + " , Trying to assign " + lType + " with " + rType); } } void makeSymbol(SymbolInfoNode *src, SymbolInfoNode *dest){ if(dest){ src->setName(dest->getName()); src->setLineBegin(dest->getLineBegin()); src->dataType = dest->dataType; src->symbol = dest->symbol; src->code = dest->code ; } } void makeUnion(SymbolInfoNode *src, SymbolInfoNode *dest){ if(dest){ src->setName(src->getName() + dest->getName()); src->setLineBegin(max(src->getLineBegin(), dest->getLineBegin())); src->code += dest->code; } } void operate(SymbolInfoNode *src, SymbolInfoNode *node1, SymbolInfoNode *operation, const BisonUtil &butil){ butil.printSemantic("----------------->>Inside sutil.operate ... printing node1 =" + node1->getPrintForTable() + "\nPrinting *operation =" + operation->getPrintForTable()); SymbolInfoNode *res = butil.searchForUndeclaredID(node1); butil.printSemantic("===>>>printin res =" + res->getPrintForTable()); string newVal ; string op = operation->getType(); if(res->equals(node1)){ newVal = operate(res, op); res->actualValue = newVal; //src->makeNode(res); //makeSymbol(src, node1); makeUnion(src, operation); } else{ butil.printError("SEMANTIC Error at line " + getString(node1->getLineBegin()) + " , variable " + node1->getName() + " is undeclared"); } } string operate(SymbolInfoNode *node1, string operation){ string thisValue = node1->actualValue; string newValue = DUMMY; string dataType = node1->dataType; if(dataType == "FLOAT"){ if(operation == "INCOP"){ float newVal = converter.stringToFloat(thisValue); newVal++; newValue = converter.floatToString(newVal); } else if(operation == "DECOP"){ float newVal = converter.stringToFloat(thisValue); newVal--; newValue = converter.floatToString(newVal); } } else if(dataType == "INT"){ if(operation == "INCOP"){ int newVal = converter.stringToInteger(thisValue); newVal++; newValue = converter.integerToString(newVal); } else if(operation == "DECOP"){ int newVal = converter.stringToInteger(thisValue); newVal--; newValue = converter.integerToString(newVal); } } return newValue; } void makeMulop(SymbolInfoNode *src, SymbolInfoNode *nodeLeft, SymbolInfoNode *nodeRight, SymbolInfoNode *operation, const BisonUtil &butil){ string op = operation->getName(); if(nodeLeft->getType() != "CONST_INT"){ if(nodeLeft->getType() != "CONST_FLOAT"){ nodeLeft = butil.searchForUndeclaredID(nodeLeft); } } if(nodeRight->getType() != "CONST_INT"){ if(nodeRight->getType() != "CONST_FLOAT"){ nodeRight = butil.searchForUndeclaredID(nodeRight); } } string lhsType = nodeLeft->dataType; string rhsType = nodeRight->dataType; string s = "===>>>>>>>>>>>>Inside makeMulop ... printing nodeLeft, nodeRight, operation\n"; s += nodeLeft->getPrintForTable(); s += "\n"; s += nodeRight->getPrintForTable(); s += "\n"; s += operation->getPrintForTable(); string x = "\nlhsType = " + lhsType + " , rhsType = " + rhsType; s += x; s += "\n=----------------== DONE ==-------------------=\n"; butil.printSemantic(s); if(op == "%"){ //Check both sides integer or not if((lhsType != "INT")||(rhsType != "INT")){ //BOTH SIDES ARE NOT INTEGERS of MOD OPERATION.. butil.printError("SEMANTIC Error at line. " + butil.getString(nodeLeft->getLineBegin()) + " , Both sides of modulus operator are not integer."); return ; } int lVal = converter.stringToInteger(nodeLeft->actualValue); int rVal = converter.stringToInteger(nodeRight->actualValue); int resVal ; if(rVal == 0){ butil.printZero("ERROR, Trying to mod by 0 at line. " + butil.getString(nodeRight->getLineBegin())); resVal = -1; }else{ resVal = lVal % rVal; } string newString = converter.integerToString(resVal); src->actualValue = newString; src->dataType = "INT"; butil.printSemantic("===>>>>>After MULOP ... printing without fullName\n$$=" + src->getPrintForTable()); } else if(op == "*"){ //Multiplication operation.. butil.printSemantic("--->>> INSIDE MULOP(*) .. printing nodeLeft and nodeRight actualValues : "); butil.printSemantic( nodeLeft->actualValue + " , " + nodeRight->actualValue); string finalDataType ; string result ; if(nodeLeft->dataType == "INT"){ int lVal = converter.stringToInteger(nodeLeft->actualValue); if(nodeRight->dataType == "INT"){ //int * int int rVal = converter.stringToInteger(nodeRight->actualValue); int res = lVal * rVal; result = converter.integerToString(res); finalDataType = "INT"; } else{ int rVal = converter.stringToFloat(nodeRight->actualValue); float res = lVal * rVal; result = converter.floatToString(res); finalDataType = "FLOAT"; } } else if(nodeLeft->dataType == "FLOAT"){ float lVal = converter.stringToFloat(nodeLeft->actualValue); if(nodeRight->dataType == "INT"){ //float * int int rVal = converter.stringToInteger(nodeRight->actualValue); float res = lVal * rVal; result = converter.floatToString(res); finalDataType = "FLOAT"; } else{ //float * float float rVal = converter.stringToFloat(nodeRight->actualValue); float res = lVal * rVal; result = converter.floatToString(res); finalDataType = "FLOAT"; } } src->actualValue = result; src->dataType = finalDataType; butil.printSemantic("===>>>After MULOP (*) .. printing $$ =" + src->getPrintForTable()); } else if(op == "/"){ float lVal = converter.stringToFloat(nodeLeft->actualValue); float rVal = converter.stringToFloat(nodeRight->actualValue); float res ; if(rVal == 0){ butil.printZero("ERROR, Trying to divide by 0 at line. " + butil.getString(nodeRight->getLineBegin())); res = -1; }else{ res = lVal / rVal; } string result = converter.floatToString(res); string finalDataType = "FLOAT"; src->actualValue = result; src->dataType = finalDataType; butil.printSemantic("===>>>After MULOP (/) .. printing $$ =" + src->getPrintForTable()); } } void unaryOperation(SymbolInfoNode *src, SymbolInfoNode *node, SymbolInfoNode *operation, const BisonUtil &butil){ string finalRes ; string finalDataType ; if(node->getType() == "CONST_FLOAT"){ finalDataType = "FLOAT"; } else if(node->getType() == "CONST_INT"){ finalDataType = "INT"; } else if(node->getType() == "ID"){ node = butil.searchForUndeclaredID(node); } if(operation->getName() == "-"){ float val = converter.stringToFloat(node->actualValue); val = (-1)*val; finalRes = converter.floatToString(val); finalDataType = node->dataType; } else if(operation->getName() == "!"){ float val = converter.stringToFloat(node->actualValue); int res; if(val != 0){ res = 0; }else{ res = 1; } finalRes = converter.integerToString(res); finalDataType = "INT"; } src->actualValue = finalRes; src->dataType = finalDataType; string s = "=======>>>>> ====>>>> AFTER unaryOperation \n" + node->getPrintForTable() + " \n" ; s += "\nSrc =" + src->getPrintForTable(); butil.printSemantic(s); } SymbolInfoNode *getNode(SymbolInfoNode * node, const BisonUtil &butil){ butil.printSemantic("DEBUGGING Line 457 Inside getNode .. node =" + node->getPrintForTable()); if(node->getType() != "ID"){ return node; } SymbolInfoNode *res = butil.searchForUndeclaredID(node); return res ; } void addSpace(SymbolInfoNode *src){ src->setName(src->getName() + " "); } void relAndLogicOp(SymbolInfoNode *src, SymbolInfoNode *lNode, SymbolInfoNode *rNode, SymbolInfoNode *operation, const BisonUtil &butil){ lNode = getNode(lNode, butil); rNode = getNode(rNode, butil); string finalRes; string finalDataType = "INT"; //RELOP RESULT'S DATA TYPE IS INT string op = operation->getName(); float lVal = converter.stringToFloat(lNode->actualValue); float rVal = converter.stringToFloat(rNode->actualValue); int res; if(op == "<"){ res = (lVal < rVal) ; } else if(op == "<="){ res = (lVal <= rVal) ; } else if(op == ">"){ res = (lVal > rVal) ; } else if(op == ">="){ res = (lVal >= rVal) ; } else if(op == "=="){ res = (lVal == rVal) ; } else if(op == "!="){ res = (lVal != rVal) ; } else if(op == "&&"){ if((lVal == 0) || (rVal == 0)){ res = 0; }else{ res = 1; } } else if(op == "||"){ if((lVal != 0) || (rVal != 0)){ res = 1; }else{ res = 0; } } finalRes = converter.integerToString(res); src->dataType = finalDataType; src->actualValue = finalRes; string s = "=======>>>>> ====>>>> AFTER relAndLogicOp of \n" + lNode->getPrintForTable() + " \n" + rNode->getPrintForTable(); s += "\nSrc =" + src->getPrintForTable(); butil.printSemantic(s); } SymbolInfoNode * checkDeclaredIDArray(SymbolInfoNode *arrayName, const BisonUtil &butil, bool doWePrint) { string name = arrayName->getName(); SymbolInfoNode *res = butil.tab->LookUp(name); butil.printSemantic("=====?????----->>>>>>> INSIDE checkDeclaredIDArray ... \nprinting arrayName name =" + name + "\narrayName =" + arrayName->getPrintForTable()); string str = "++--------===++===>>Inside checkDeclaredIDArray ... printing ST\n"; str += butil.tab->printCurrentNonEmpty(); butil.printSemantic(str); if(!res){ if(doWePrint){ butil.printError("SEMANTIC Error at line. " + butil.getString(arrayName->getLineBegin()) + ", variable with name =" + name + " was not declared\n"); } butil.printSemantic("NAME " + name + " DOESNOT EXIST in ST."); return 0; } else{ //Check whether array or not. butil.printSemantic("=====?????----->>>>>>> INSIDE checkDeclaredIDArray ... printing res =" + res->getPrintForTable()); bool flag = res->isArray; if(flag == false){ if(doWePrint){ butil.printError("Semantic Error, Trying to use ID " + name + " as an array in line. " + butil.getString(arrayName->getLineBegin()) + " but it was not declared as an array at line." + butil.getString(res->getLineBegin())); } return 0; } //Check for function name. if(name == butil.currentFunctionName){ if(doWePrint){ butil.printError("Semantic Error, Trying to use ID " + name + " as an array int line. " + butil.getString(arrayName->getLineBegin())+ " but it is a function in line. " + butil.getString(butil.currentFunctionLine)); } return 0; } //Check for parameters. for(int i=0; i<(int)butil.currentFunctionList.size(); i++){ if(butil.currentFunctionList[i]->getName() == name){ if(doWePrint){ butil.printError("SEMANTIC Error, Array name = " + name + " is same as name of parameter of function " + butil.currentFunctionName + " at line. " + butil.getString(butil.currentFunctionLine)); } return 0; } } //CHANCES OF SEGMENTATION FAULT ... THEN return arrayName instead of res. //arrayName->makeNode(res); return res; } return 0; } void checkForArrayExpression(SymbolInfoNode* arrayName, SymbolInfoNode* expression, const BisonUtil &butil){ SymbolInfoNode *res = checkDeclaredIDArray(arrayName, butil, true); if(!res){ //DO NOTHING .. }else{ arrayName->makeNode(res); } string rhsType = expression->dataType; string lhsType = arrayName->dataType; string s = "---->>> Inside checkForArrayExpression ... printin array\n"; s += arrayName->getPrintForTable(); s += "\nPrinting expression\n"; s += expression->getPrintForTable(); s += "\n=======>>> DONE WITH THIS SHIT NOW CHECKING FOR INVALID dataType\n"; butil.printSemantic(s); bool flag = (rhsType == "FLOAT") || (rhsType == "INT") ; bool flag2 = (lhsType == "FLOAT") || (lhsType == "INT") ; if(!((flag == true) && (flag2 == true))){ //Invalid data Type butil.printSemantic("INVALID DATA TYPE IN checkForArrayExpression function LINE 483, dataType lhs/arrayName = " + lhsType + ", dataType rhsType/expression = " + rhsType); return; } /*if(lhsType == "FLOAT"){ return; }*/ if(arrayName->isArray == false){ butil.printError("SEMANTIC Error, Trying to use third braces without declaring as an array in line. " + butil.getString(arrayName->getLineBegin())); } /*if((rhsType != "INT")){ butil.printError("SEMANTIC Error, The index of array " + arrayName->getName() + " is not an integer expression at line " + butil.getString(arrayName->getLineBegin())); }*/ } bool isDuplicate(SymbolInfoNode *node, const BisonUtil &butil){ SymbolInfoNode *res = butil.tab->searchCurrent(node); //Search for multiple declaration in same scope string name = node->getName(); if(res){ butil.printError("SEMANTIC Error[Duplicate definition of array], variable named " + node->getName() + " was declared in line no. " + butil.getString(res->getLineBegin())); return true; } else{ if(name == butil.currentFunctionName){ butil.printError("SEMANTIC Error[Duplicate definition of array, array name same as function name], variable named " + node->getName() + " was declared/defined in line no. " + butil.getString(butil.currentFunctionLine)); return true; } for(int i=0; i<(int)butil.currentFunctionList.size(); i++){ if(butil.currentFunctionList[i]->getName() == name){ butil.printError("SEMANTIC Error[Array name = " + name + " is same as name of parameter of function " + butil.currentFunctionName + "] at line. " + butil.getString(butil.currentFunctionLine)); return true; } } } butil.printSemantic("-------===>>>> Inside isDuplicate .. printin Node =" + node->getName() + " and returning false <<====== \n"); return false; } void pushArray(SymbolInfoNode *node, SymbolInfoNode *sizeNode,const BisonUtil &butil){ int size = butil.getSize(sizeNode -> getName()); node->isArray = true ; node->arrayItems.size = size; node->arrayItems.arrayName = node->getName(); butil.tab->Insert(node); /*butil.tab->Insert(node->getName(), node->getType(), node->dataType, node->getLineBegin(), node->isArray, node->isFunction, node->actualValue, node->functionItems, node->arrayItems);*/ string s = "====++>>>>>> AFTER pushArray ... printing symbol table.. "; s += butil.tab->printCurrentNonEmpty(); s += "\n ======== >>> DONE WITH pushArray <<< =========\n"; butil.printSemantic(s); } void makeSymbol(SymbolInfoNode *src, SymbolInfoNode *n1, SymbolInfoNode *n2, SymbolInfoNode *n3, SymbolInfoNode *n4, const BisonUtil &butil){ string prevName = n1->getName(); string name = n1->getName() + n2->getName() + n3->getName() + n4->getName(); src->setName(name); src->setLineBegin(min((min(n1->getLineBegin(), n2->getLineBegin()), n3->getLineBegin()) , n4->getLineBegin() )); src->dataType = n1->dataType; src->isArray = true; src->arrayItems.size = butil.getSize(n3); src->arrayItems.arrayName = n1->getName(); n1->setName(prevName); if(n1 && n2 && n3 && n4){ src->symbol = n1->symbol; src->code = (n1->code + n2->code + n3->code + n4->code); } } string checkWhetherArgumentsMatch(SymbolInfoNode *functionNode, SymbolInfoNode *functionDefined , SymbolInfoNode *argumentList, const BisonUtil &butil){ string s = "=====-----+++++----->>>> Inside sutil.checkWhetherArgumentsMatch ... printing\n"; s += "functionNode ="; s += functionNode->getPrintForTable(); s += "\nfunctionDefined ="; s += functionDefined->getPrintForTable(); s += "\nargumentList ="; s += butil.currentArgumentList.getArgumentList(); s += "\nparameterList ="; s += functionDefined->functionItems.getFunction(); s += "\n\n"; butil.printSemantic(s); butil.printSemantic("======+>>> sutil Line 746 checkWhetherArgument match done . "); FunctionItems fun = functionDefined->functionItems; if(fun.returnType == "VOID"){ string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , trying to use void function as part of expression."; str += " with name = "; str += fun.functionName; str += " which was defined at line no."; str += converter.integerToString(fun.lineNumberBegin); //butil.printError(str); this->errorVoid = str ; functionNode->dataType = functionDefined->functionItems.returnType; return "ERROR"; } int sizeArguments = (int)butil.currentArgumentList.listArguments.size(); int sizeParam = (int)fun.list.size(); butil.printSemantic("======+>>> sutil Line 762 done . "); if(sizeParam != sizeArguments){ string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , function call parameter size and argument size doesnot match."; str += " function was defined/declared at line no."; str += converter.integerToString(fun.lineNumberBegin); butil.printError(str); butil.printSemantic("======+>>> sutil Line 772 done . "); return "ERROR"; } butil.printSemantic("======+>>> sutil Line 774 done . "); for(int i=0; i<sizeArguments; i++){ if(fun.list[i].type != butil.currentArgumentList.listArguments[i].type) { //|| (fun.list[i].isArray != butil.currentArgumentList.listArguments[i].isArray)) string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , function call parameter and arguments type mismatch."; str += " function was defined/declared at line no."; str += converter.integerToString(fun.lineNumberBegin); butil.printError(str); return "ERROR"; } } butil.printSemantic("======+>>> sutil Line 789 done returning fun.returnType = " + fun.returnType); return fun.returnType; } string functionCall(SymbolInfoNode *src, SymbolInfoNode *functionNode, SymbolInfoNode *argumentList, const BisonUtil &butil){ string s = "+++====--->>>Inside sutil.functionCall .. printing <<<>><=====\nfunctionNode ="; s += functionNode->getPrintForTable(); s += "\nargumentList ="; if(argumentList){ s += argumentList->getPrintForTable(); }else{ s += " EMPTY ARGUMENTS.. "; } s += "\n <========= <<< DONE in functionCall >>> ==========>\n"; butil.printSemantic(s); SymbolInfoNode *functionChecker = butil.tab->LookUp(functionNode->getName()); if(functionChecker){ butil.printSemantic("----=====+++++====>>>> Printing functionChecker =" + functionChecker->getPrintForTable()); }else{ butil.printSemantic("==>> Inside sutil.functionCall .. NOT FOUND WITH THAT NAME " + functionNode->getName()); } if(functionChecker){ //Check whether it is a function or not. if(functionChecker->isFunction == false){ butil.printSemantic("\n===>>INSIDE functionChecker does exist and is not a function !!\n"); butil.printSemantic("<><>==>> functionChecker is not a function !!"); string str = "SEMANTIC ERROR, ID with name = "; str += functionChecker->getName(); str += " was not declared as function in line. "; str += converter.integerToString(functionChecker->getLineBegin()); str += " , but is being used as a function in line. "; str += converter.integerToString(functionNode->getLineBegin()); butil.printError(str); return "ERROR"; }else{ butil.printSemantic("---->>>> INSIDE functionCall ... found in ST and printing\n", functionNode); //if(functionChecker->functionItems.declareOrDefine == "DECLARE"){ if(false){ string err = "SEMANTIC ERROR at line. " + converter.integerToString(functionNode->getLineBegin()) ; err += " , function with name " ; err += functionNode->getName(); err += " was not defined."; butil.printError(err); return "ERROR"; } return checkWhetherArgumentsMatch(functionNode, functionChecker, argumentList, butil); } } else{ //CHECK FOR CURRENT FUNCTION string flag3 = checkForRecursion(functionNode, argumentList, butil); if((flag3 == "ERROR") || (flag3 == "RECURSION")){ //This is recursion .. butil.printSemantic("---->>>==>>> Line 866.. recursion Occurs."); return "RECURSION"; }else{ string str = "SEMANTIC ERROR, function with name = "; str += functionNode->getName(); str += " at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , was not declared before."; butil.printError(str); butil.printSemantic("------>>>> INSIDE functionCall ... not found in ST hence error."); return "ERROR"; } } return "ERROR"; } string checkForRecursion(SymbolInfoNode *functionNode, SymbolInfoNode *argumentList, const BisonUtil &butil){ string s = "\n\n=====-----+++++----->>>> Inside sutil.checkForRecursion ... printing <<<=============\n"; s += "functionNode ="; s += functionNode->getPrintForTable(); s += "\nSize of argumentList = "; s += butil.getString((int)butil.currentArgumentList.listArguments.size()); s += "\nargumentList ="; s += butil.currentArgumentList.getArgumentList(); s += "\nCurrent function name ="; s += butil.currentFunctionName; s += "\nSize of current function parameter List = "; s += butil.getString((int)butil.currentFunctionList.size()); s += "\nCurrent parameterList ="; for(int i=0; i<(int)butil.currentFunctionList.size(); i++){ s += butil.currentFunctionList[i]->getPrintForTable(); s += "\t"; } s += "\n\n<< Line 897 Hoise ... >>\n\n"; butil.printSemantic(s); bool isRecursion = false ; //CHECKING WHETHER RECURSION HOISE ... if(functionNode->getName() == butil.currentFunctionName){ //Function names match ... butil.printSemantic("FUNCTION NAMES FOR RECURSION MATCHED !!"); isRecursion = true ; } if(!isRecursion){ return "NAMES_DONT_MATCH" ; } //<NAME> butil.printSemantic("butil.currentFunctionReturnType = " + butil.currentFunctionReturnType); if((butil.currentFunctionReturnType == "VOID") || (butil.currentFunctionReturnType == "void")){ string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , trying to use void function as part of expression."; str += " with name = "; str += functionNode->getName(); str += " which was defined at line no."; str += converter.integerToString(butil.currentFunctionLine); this->errorVoid = str ; butil.printSemantic("Line 931 .. checkForRecursion .. setting errorVoid = " + errorVoid); return "ERROR" ; }//This if was for void function as part of expression thing. //Now Comparing arguments .. int sizeArguments = (int)butil.currentArgumentList.listArguments.size(); int sizeParam = (int)butil.currentFunctionList.size(); //Comparing size of argument list and parameter list.. if(sizeParam != sizeArguments){ string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , function call parameter size and argument size do not match."; str += " function was defined at line no."; str += converter.integerToString(butil.currentFunctionLine); butil.printError(str); return "ERROR" ; } //Comparing types. ... for(int i=0; i<sizeArguments; i++){ if(butil.currentFunctionList[i]->getType() != butil.currentArgumentList.listArguments[i].type) { //||(butil.currentFunctionList[i]->isArray != butil.currentArgumentList.listArguments[i].isArray)){ string str = "SEMANTIC ERROR, at line. "; str += converter.integerToString(functionNode->getLineBegin()); str += " , function call parameter and arguments type mismatch."; str += " function was defined at line no."; str += converter.integerToString(butil.currentFunctionLine); butil.printError(str); return "ERROR" ; } } //<NAME> return "RECURSION" ; } void pushCurrentParameters(const BisonUtil &butil) { string s = "\n====>>>> sutil.pushCurrentParameters ... "; s += "\nCurrent Func name =" ; s += butil.currentFunctionName; s += "\nCurrent Scope Table ID = "; s += converter.integerToString(butil.tab->getCurrentScopeID()); s += "\nparameterList size = "; s += converter.integerToString((int)butil.currentFunctionList.size()); s += "\nparameterList is:\n"; for(int i=0; i<(int)butil.currentFunctionList.size(); i++){ //s += butil.currentFunctionList[i]->getPrintForTable(); butil.tab->Insert(butil.currentFunctionList[i]); //s += "\n"; } s += "\nAfter pushing, Printing ST now .. \n"; s += butil.tab->printAllNonEmpty(); s += "\n===========>>> DONE WITH sutil.pushCurrentParameters ... <<<<==================\n"; butil.printSemantic(s); } SymbolInfoNode *makeNewNode(string name, string type){ SymbolInfoNode *node = new SymbolInfoNode(name, type); return node ; } //EKDOM LATEST EDIT void makeArrayExpression(SymbolInfoNode *array, SymbolInfoNode *expression, const BisonUtil &butil){ butil.printArrayDebug("INSIDE makeArrayExpression... expression is " + expression->getName() + " , and dataType = " + expression->dataType); string lName = ""; for(int i=0; i<array->getName().length(); i++){ if(array->getName()[i] == '['){ break; }else{ lName += array->getName()[i]; } } if(expression->dataType != "INT"){ if(expression->dataType != "NIL"){ butil.printError("SEMANTIC ERROR at line. " + converter.integerToString(array->getLineBegin()) + ", the index of array " + lName +" is not an integer."); } } } void makeGoodType(SymbolInfoNode *arr, const BisonUtil &butil){ string name = getArrayName(arr->getName()); SymbolInfoNode *res = butil.tab->LookUp(name); string dataType = "NIL"; if(res){ arr->dataType = res->dataType; arr->symbol = res->symbol; arr->code = res->code; //butil.printArrayDebug("Inside makeGoodType ... printing arr , and res "); //butil.printArrayDebug(arr->getPrintForTable()); //butil.printArrayDebug(res->getPrintForTable()); } } string getArrayName(string arr){ string lName = ""; for(int i=0; i<arr.length(); i++){ if(arr[i] == '['){ break; }else{ lName += arr[i]; } } return lName; } bool getArgument( SymbolInfoNode *node,const BisonUtil &butil){ butil.printArrayDebug("Inside getArgument... node = " + node->getPrintForTable()); SymbolInfoNode *res = butil.tab->LookUp(node->getName()); if(res){ node->isArray = res->isArray; string s = butil.tab->printCurrentNonEmpty(); butil.printArrayDebug(s); butil.printArrayDebug("Got RES , res = " + res->getPrintForTable()); return true ; } return false ; } }; //END<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> using namespace std ; std::string numToString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } class Utility { //SymbolTable *tab ; ofstream tokenout; ofstream logout ; int beginCommentLine ; int beginSlashCommentLine ; string commentString ; string slashComment; int unfinishedStringLine; string unfinishedString; int unfinishedCommentLine; string unfinishedComment; int increaseInLineCount ; public: Utility( ) { commentString = ""; slashComment = ""; unfinishedString = "" ; unfinishedComment = ""; // tokenout= fopen("token.txt","w"); tokenout.open("Lexical_Stuffs/1505022_token.txt"); // ../doc/my_file.txt logout.open("Lexical_Stuffs/1505022_log.txt"); //tab = new SymbolTable(50); //tab->enterScope(); increaseInLineCount = 0 ; } /* ~Utility() { if(tab) delete tab ; tab = 0 ; } */ void closeFiles() { // fclose(tokenout); tokenout.close(); logout.close(); } string getStringFromChar(char *ptr) { string s = ""; if(ptr != 0) s.push_back(ptr[1]); return s; } string getStringFromPointer(char *ptr) { char ch ; bool flag = false ; int id = strlen(ptr); // printf("\nInside getCharFromPointer function ... strlen = %d\n", id); string x = ""; if(strlen(ptr) == 3) { ch = ptr[1]; flag = true ; } else if(strlen(ptr) == 4) { char c = ptr[2] ; if(c == 'n') { ch = '\n'; flag = true; } else if(c == 't') { ch = '\t'; flag = true; } else if (c == '\\') { ch = '\\'; flag = true; } else if(c == 'a') { ch = '\a'; flag = true; } else if(c == 'f') { ch = '\f'; flag = true; } else if(c == 'r') { ch = '\r'; flag = true; } else if(c == 'b') { ch = '\b'; flag = true; } else if(c == 'v') { ch = '\v'; flag = true; } else if(c == '0') { ch = '\0'; flag = true; } else if(c == '\'') { ch = '\''; flag = true ; } } else if(strlen(ptr) == 5) { x.push_back(ptr[2]); x.push_back(ptr[3]); } if(flag == false){ // printf("FLAG = FALSE .. ptr[0] = %c, ptr[1] = %c, ptr[2] = %c, ptr[3] = %c, ptr[4] = %c\n", ptr[0], // ptr[1], ptr[2], ptr[3], ptr[4]); return x ; } else { // printf("FLAG = TRUE .. ptr[0] = %c, ptr[1] = %c, ptr[2] = %c, ptr[3] = %c\n", ptr[0], // ptr[1], ptr[2]); string s(1, ch); return s ; } } char getCharacter(char *ptr) { bool flag = false ; /// FOR '\n' type char ch ; char *singleChar = 0; char *doubleChar = 0; // cout << "\nINSIDE getCharacter(" << ptr << ")" << endl ; if(strlen(ptr) <= 3) { char c = ptr[1] ; if(c == 'n') { ch = '\n'; flag = true; } else if(c == 't') { ch = '\t'; flag = true; } else if (c == '\\') { ch = '\\'; flag = true; } else if(c == 'a') { ch = '\a'; flag = true; } else if(c == 'f') { ch = '\f'; flag = true; } else if(c == 'r') { ch = '\r'; flag = true; } else if(c == 'b') { ch = '\b'; flag = true; } else if(c == 'v') { ch = '\v'; flag = true; } else if(c == '0') { ch = '\0'; flag = true; } else if(c == '\'') { ch = '\''; flag = true ; } else if(c == '\"') { ch = '\"'; flag = true ; } } return ch ; } void print(char *ptr) { string s = getStringFromPointer(ptr); // cout << endl << "+==>> INSIDE TryTests.cpp , STR LEN = " << strlen(ptr) << " Util ... util.print(ptr) ... s = " << s << "|||DONE" << endl; } string getFullTokenNormal(string tokenname, string lexemename) { string fullTokenName = ""; fullTokenName += "<"; fullTokenName += tokenname; fullTokenName += ", "; fullTokenName += lexemename; fullTokenName += ">"; return fullTokenName ; } string getFullTokenForOp(string tokenname, string lexemename) { string fullTokenName = ""; fullTokenName += "<"; fullTokenName += tokenname; fullTokenName += ", "; fullTokenName += lexemename; fullTokenName += ">"; return fullTokenName ; } void printSingleCharToFile(char *ptr, int lineNumber, string tokenName, string lexemeName) { char ch = ptr[1]; string s(1, ch); } string getKeyWordLog(int lineNumber, string token) { string s = ""; s += "Line No. "; s += numToString(lineNumber); s += ": Token "; s += token ; s += "\n"; // s += " found.\n"; return s ; } string getLogString(int lineNumber, string token, string lexeme) { string s = "" ; s += "Line No. "; s += numToString(lineNumber); s += ": Token <"; s += token; s += ">"; s += " Lexeme: "; s += lexeme ; // s += "\n"; s += " found\n"; return s ; } void printForOp(char *ytext, int lineNumber, string tokenname, string lexemename) { string fullTokenName = getFullTokenForOp(tokenname, lexemename); // cout << "\n<><><>PRINTINGI TO FILE ... " << ytext << " at lien = " << lineNumber << " , tokenNAME is " << fullTokenName << " , lex is " << lexemename << endl ; tokenout << fullTokenName << ' '; string s = getLogString(lineNumber, tokenname, lexemename); logout << s ; } void printForKeywords(char *ytext, int lineNumber, string tokenname, string lexemname) { // cout << "\n==>>PRINTING KEYWORD TO FILE ..Token = " << tokenname << " , For lexeme is " << lexemname << " , at line = " << lineNumber << endl ; string s = getKeyWordLog(lineNumber, tokenname); tokenout << tokenname << ' '; logout << s ; // tokenout << "\n==>>PRINTING KEYWORD TO FILE ..Token = " << tokenname << " , For lexeme = " << lexemname << " , at line = " << lineNumber << endl ; } void printLiteral(char *ytext, int lineNumber, string tokenname, string tokenValue,string lexemname) { string x = getFullTokenNormal(tokenname, tokenValue); //tab->Insert(tokenValue,tokenname); //string s = tab->printCurrentNonEmpty(); //cout << s << endl ; // cout << "\n==>>>> PRINTING Literal to file .. Token = " << x << " , For lexeme is " << lexemname << " , at line = " << lineNumber << endl ; tokenout << x << ' '; string str = getLogString(lineNumber, tokenname, lexemname); logout << str ; // tokenout << "\n==>>>> PRINTING Literal to file .. Token = " << x << " , For lexeme = " << lexemname << " , at line = " << lineNumber << endl ; } void printIdentifier(char *ytext, int lineNumber, string tokenName, string lexemname) { string fullTokenName = getFullTokenNormal(tokenName, lexemname); string tokenValue = lexemname; // cout << "\n<><><>PRINTINGI TO FILE ... " << ytext << " at lien = " << lineNumber << " , tokenNAME is " << fullTokenName << " , lex is " << lexemname << endl ; // tab->Insert(tokenValue, tokenName); //string x = tab->printCurrentNonEmpty(); string s = getLogString(lineNumber, tokenName, tokenValue); // string s = "Line No. "; s += numToString(lineNumber); s += " : Token <" ; s += tokenName ; s += "> Lexeme "; s += tokenValue; s += " found.\n"; logout << s ; //logout << x ; tokenout << fullTokenName << ' ';// tokenout << "\n<><><>PRINTINGI TO FILE ... " << ytext << " at lien = " << lineNumber << " , tokenNAME = " << fullTokenName << " , lex = " << lexemname << endl ; } void printForCharacter(char *ytext, int lineNumber) { string tokenValue = getStringFromPointer(ytext); string tokenName = "CONST_<PASSWORD>"; // cout << "\n =====---++++>>> Printin to File ... <" << tokenName << " , " << tokenValue << ">" << endl ; string fullToken = "<"; for(int i=0; i<tokenName.size(); i++){ fullToken.push_back(tokenName[i]); } fullToken.push_back(','); fullToken.push_back(' '); for(int i=0; i<tokenValue.size(); i++){ fullToken.push_back(tokenValue[i]); } fullToken.push_back('>'); // cout << "Token name : " << tokenName <<" , TOKEN VALUE = " << tokenValue << endl ; //tab->Insert(tokenValue, tokenName); //string x = tab->printCurrentNonEmpty(); string s = getLogString(lineNumber, tokenName, tokenValue); // string s = "Line No. "; s += numToString(lineNumber); s += " : Token <" ; s += tokenName ; s += "> Lexeme "; s += tokenValue; s += " found.\n"; logout << s ; //logout << x ; tokenout << fullToken << ' '; // tokenout << "\n =====---++++>>> Printin to File ... <" << tokenName << " , " << tokenValue << ">" << endl ; } string convertedSpecialCharToken(string lexemname) { string temp = lexemname; char *ptr = new char[3]; string x = ""; // printf("><><><><><>>< INSIDE convertedSpecialCharToken... \n"); for(int i=0; i<(temp.size() - 1); i++) { if(temp[i] == '\\') { // cout << "temp[i] = \\ found ... temp[i] = " << temp[i] << " AND " ; ptr[0] = temp[i]; ptr[1] = temp[i+1]; ptr[2] = '\0'; char ch = getCharacter(ptr); // cout << " AND ch = " << ch ; i++; x.push_back(ch); } else{ x.push_back(temp[i]); } } return x ; } int getLength(char *ptr) { int len = 0; char *newPtr = new char[strlen(ptr) + 1]; int i = 0; i++ ; ///TO DISCARD FIRST " mark while(i < (strlen(ptr)-2)) { if(ptr[i] == '\\') { if(ptr[i+1] == '\n') { ///MULTI LINE STRING case ... i = i + 2 ; } else{ ///SINGLE LINE STRING BUT \n or \t i.e. special chars type things used . char *pointer = new char[3]; pointer[0] = '\\'; pointer[1] = ptr[i+1]; pointer[2] = '\0'; char ch = getCharacter(pointer); newPtr[len] = ch ; i+=2 ; len++ ; } } else { newPtr[len] = ptr[i]; len++; i++ ; } } newPtr[len++] = ptr[i++]; ///TO COPY THE LAST CHARACTER AND NOT THE " mark newPtr[len] = '\0'; // cout << "\n==>>> RETUURNING newPtr = " << newPtr << endl ; return len ; } char *getNewLine(char *ptr) { int len = 0; char *newPtr = new char[strlen(ptr) + 2]; int i = 0; // printf("\n===>>>Inside getNewline() , string is %s...\n", ptr); i++ ; ///TO DISCARD FIRST " mark while(i < (strlen(ptr)-2)) { if(ptr[i] == '\\') { if(ptr[i+1] == '\n') { ///MULTI LINE STRING case ... i = i + 2 ; // printf("A NEW LINE IS ENCOUNTERED...\n"); increaseInLineCount++ ; } else{ ///SINGLE LINE STRING BUT \n or \t i.e. special chars type things used . char *pointer = new char[3]; pointer[0] = '\\'; pointer[1] = ptr[i+1]; pointer[3] = '\0' ; char ch = getCharacter(pointer); newPtr[len] = ch ; i+=2 ; len++ ; } } else { newPtr[len] = ptr[i]; len++; i++ ; } } newPtr[len++] = ptr[i++]; ///TO COPY THE LAST CHARACTER AND NOT THE " mark newPtr[len] = '\0'; // cout << "\n==>>> RETUURNING newPtr = " << newPtr << endl ; return newPtr ; } string getString(char *ptr, int len) { string s = ""; for(int i=0; i<len; i++){ s.push_back(ptr[i]); } return s ; } void printLineString(char *ytext, int lineNumber, string tokenname, string lexemname) { if(lexemname == "\"\"") { string s = getLogString(lineNumber, tokenname, lexemname); logout << s ; string fullToken = getFullTokenForOp(tokenname, lexemname); tokenout << fullToken << ' ' ; return ; } // lexemname = convertedSpecialCharToken(lexemname); // lexemname.clear(); char *temp = getNewLine(ytext); int len = getLength(ytext); lexemname = getString(temp, len); string s = getLogString(lineNumber, tokenname, lexemname); logout << s ; string fullToken = getFullTokenForOp(tokenname, lexemname); tokenout << fullToken << ' ' ; } void printComment(char *ytext, int lineCount) { int len = strlen(ytext); // ytext[len - 1] = '\0'; ///To get rid of the last new line char //cout << "Token <COMMENT> Lexeme : " << ytext << " |||at line = " << lineCount << endl ; string s = getLogString(lineCount, "<COMMENT>", ytext); logout << s ; // cout << "\n=> Comment: \"" << ytext << "\" at line = " << lineCount << endl ; } void printCharArray(int len, char *ptr) { printf("\n"); for(int i=0; i<len; i++){ printf("%c<||||||>", ptr[i]); } printf("\n"); } ///Handle Comments... void beginComment(char *ptr, int lineNum) { commentString.clear(); for(int i=0; i<strlen(ptr); i++){ commentString.push_back(ptr[i]); } this->beginCommentLine = lineNum; } void addComment(char *yytext) { for(int i=0; i<strlen(yytext); i++){ commentString.push_back(yytext[i]); } } void printComment() { //cout << "Token <COMMENT> , Lexeme: " << commentString << " |||Found\n"; string s = getLogString(beginCommentLine, "<COMMENT>", commentString); logout << s ; commentString.clear(); } void beginSlashComment(char *yytext, int lineNumber) { slashComment.clear(); beginSlashCommentLine = lineNumber ; for(int i=0; i<strlen(yytext); i++){ slashComment.push_back(yytext[i]); } } void addSlashComment(char *yytext) { for(int i=0; i<strlen(yytext); i++){ slashComment.push_back(yytext[i]); } } void printSlashComment() { //cout << "Token <SLASH_COMMENT> , Lexeme: " << slashComment << " |||Found\n"; string s = getLogString(this->beginSlashCommentLine, "<COMMENT>", slashComment); logout << s ; slashComment.clear(); } void beginUnfinishedString(int lineNumber) { unfinishedStringLine = lineNumber ; unfinishedString.clear(); } void addUnfinishedString(char *yytext) { for(int i=0; i<strlen(yytext); i++){ unfinishedString.push_back(yytext[i]); } } string getErrorLog(int line, string errorMessage, string toPrint) { string s = "ERROR AT "; s += "Line No. "; s += numToString(line); s += " "; s += errorMessage; s += " "; s += toPrint ; s += "\n"; return s ; } void printUnfinishedString() { string s = getErrorLog(unfinishedStringLine,"Unfinished String",unfinishedString); logout << s ; unfinishedString.clear(); } void beginUnfinishedComment(int line) { this->unfinishedCommentLine = line ; unfinishedComment.clear(); } void addUnfinishedComment(char *yytext) { for(int i=0; i<strlen(yytext); i++){ unfinishedComment.push_back(yytext[i]); } } void printUnfinishedComment() { string s = getErrorLog(unfinishedCommentLine,"Unfinished COMMENT",unfinishedComment); logout << s ; unfinishedComment.clear(); } void destroyUnfinishedComment() { unfinishedComment.clear(); } void printError(int line, string errorType, char *ytext) { string x = ""; for(int i=0; i<strlen(ytext); i++){ x.push_back(ytext[i]); } string s = getErrorLog(line, errorType, x); logout << s ; } int printCharError(int line, string errorType, char *ytext) { int inc_line = 0; for(int i=0; i<strlen(ytext)-1; i++){ if(ytext[i] == '\\') { if(ytext[i+1] == '\n') { inc_line ++ ; } } } printError(line, errorType, ytext); return inc_line ; } void printEOF(int line_cnt, int error) { string s = ""; s += "TOTAL LINE NUMBER : " ; s += numToString(line_cnt); s += " , TOTAL ERRORS : "; s += numToString(error); s += "\n"; logout << s << endl ; } int getIncreaseInLineCount() { return increaseInLineCount ; } void makeIncreaseInLine(int val) { increaseInLineCount = val ; } }; /* FOR WINDOWS.. flex 1505022.l g++ lex.yy.c -L"C:\Program Files (x86)\GnuWin32\lib" -lfl -o test.exe test.exe 1505022_Input.txt pause */ /* FOR LINUX .. flex -o output.cpp 1505022.l g++ output.cpp -lfl -o out.out ./out.out 1505022_Input.txt */ <file_sep>int max(int x, int y); int func(int a, int b, int c){ if(a >= b){ return max(a, c); } else{ return max(b, c); } } int main() { int a, b, c; a = func(1, 2, 3); println(a); int arr[10]; int i; for(i=0; i<10; i++){ arr[i] = 10-i; } b = func(arr[0], arr[4], arr[6]); println(b); } int max(int x, int y){ if(x >= y){ return x; } return y; } <file_sep> #include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include "1505022_SymbolInfo.h" using namespace std ; class ScopeTableNode { private: int numberOfBuckets; //Array Of Pointers of SymbolInfoNode i.e. double pointers each single pointed to initially 1. SymbolInfoNode **array_of_pointers ; int uniqueID ; ScopeTableNode *parentScope; public: static int global_scope ; //Constructor std::string numToStringInST ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } ScopeTableNode() { array_of_pointers = 0; parentScope = 0; } ScopeTableNode(int n) { numberOfBuckets = n; uniqueID = 0; // current_scope_number++ ; initialiseArray(n); parentScope = 0; } ScopeTableNode(int n, int id) { numberOfBuckets = n; uniqueID = id; // current_scope_number = id + 1 ; initialiseArray(n); parentScope = 0; } //Destructor ~ScopeTableNode() { // //printf("++-->>Calling destructor for id = %d\n", getID()); if(array_of_pointers) delete [] array_of_pointers ; array_of_pointers = 0 ; if(parentScope) delete parentScope ; parentScope = 0; } //Functions int getNumberOfBuckets(){return numberOfBuckets;} void initialiseArray(int n) { array_of_pointers = new SymbolInfoNode*[n]; for(int i=0; i<n; i++){ array_of_pointers[i] = new SymbolInfoNode(); /// dummy nodes. } } int getID(){return uniqueID;} int hash2(string s){ // char a[s.size() + 1] ; char *a = new char[s.size() + 1]; copy(s.begin(), s.end(), a); long long int tot = 0; for(int i=0; i<s.size(); i++) { tot += a[i]*pow(prime_number, i); tot = tot%numberOfBuckets ; // //printf("tot += a[i]*pow(prime_number, i); =--> %d += %d*pow(%d, %d)\n", tot, a[i], prime_number, i); } int final = (int) ( tot%numberOfBuckets ) ; return final ; } int hashFunction(string s) { return hash2(s); // char a[s.size() + 1] ; char *a = new char[s.size() + 1]; copy(s.begin(), s.end(), a); // printArray(a, s.size()); int tot = 0; for(int i=0; i<s.size(); i++) { tot += a[i]*pow(prime_number, i); // //printf("tot += a[i]*pow(prime_number, i); =--> %d += %d*pow(%d, %d)\n", tot, a[i], prime_number, i); } tot = tot%numberOfBuckets ; // //cout << "tot = " << tot << endl ; return tot ; } SymbolInfoNode *lookup(string s) { int idx = hashFunction(s); SymbolInfoNode *nullNode = 0; SymbolInfoNode *head = array_of_pointers[idx]; int pos = lookup(s, idx); if(pos == -1){ //printf("\tNot Found in ScopeTableNode #%d\n", uniqueID); return nullNode ; } else{ //printf("\tFound in ScopeTableNode #%d at position %d, %d\n", uniqueID, idx, pos); while(head != 0){ if(head->getName() == s) return head ; head = head -> getNext(); } } return 0 ; } int lookup(string s, int index) { SymbolInfoNode *head = array_of_pointers[index]; ///Then Search head of that linked list. int cnt = -1; while(head != 0) { if(head->getName() == s) return cnt ; else{ head = head->getNext(); cnt++; } } return -1 ; } bool insert(string s, string type ) { int flag = lookup(s, hashFunction(s)); if(flag != -1)///already exists{ { SymbolInfoNode x(s, type); //printf(" "); x.printForTable(); //printf(" already exists in ScopeTableNode # %d at position %d, %d\n", uniqueID, hashFunction(s), flag); return false ; } int f = insert(s,type,hashFunction(s)); //printf(" Inserted in ScopeTableNode # %d at position %d, %d\n", uniqueID, hashFunction(s), f); return true; } //LATEST SHITASS bool insert(string symbol_name, string symbol_type, string dataType, int lineBeg, bool isArray, bool isFunction, string actualValue, FunctionItems f, ArrayItems a) { int flag = lookup(symbol_name, hashFunction(symbol_name)); if(flag != -1)///already exists{ { SymbolInfoNode x(symbol_name, symbol_type); //printf(" "); x.printForTable(); //printf(" already exists in ScopeTableNode # %d at position %d, %d\n", uniqueID, hashFunction(symbol_name), flag); return false ; } int index = hashFunction(symbol_name); SymbolInfoNode *ptr = array_of_pointers[index]; SymbolInfoNode *newNode = ptr->makeNewNode(symbol_name, symbol_type); newNode->dataType = dataType; newNode->setLineBegin(lineBeg); newNode->isArray = isArray; newNode->isFunction = isFunction; newNode->actualValue = actualValue; if(newNode->isFunction == true){ newNode->functionItems.changeFunction(f); } if(newNode->isArray == true){ newNode->arrayItems.changeArray(a); } int cnt = 0; while(ptr->getNext() != 0){ ptr = ptr->getNext(); cnt++ ; } ///Go to the very end .. ptr->setNext(newNode); newNode->setNext(0); return cnt ; } int insert(string s, string type, int index) { SymbolInfoNode *ptr = array_of_pointers[index]; ///get the SymbolInfo pointer of the array of pointers... SymbolInfoNode *newNode = ptr->makeNewNode(s, type); // //printf("Inside insert at idx = %d.. newNode is ", index); newNode->printNode(); int cnt = 0; while(ptr->getNext() != 0){ ptr = ptr->getNext(); cnt++ ; } ///Go to the very end .. ptr->setNext(newNode); newNode->setNext(0); return cnt ; } int insert(SymbolInfoNode *newNode, int index) { SymbolInfoNode *ptr = array_of_pointers[index]; ///get the SymbolInfo pointer of the array of pointers... //SymbolInfoNode *newNode = ptr->makeNewNode(s, type); // //printf("Inside insert at idx = %d.. newNode is ", index); newNode->printNode(); int cnt = 0; while(ptr->getNext() != 0){ ptr = ptr->getNext(); cnt++ ; } ///Go to the very end .. ptr->setNext(newNode); newNode->setNext(0); return cnt ; } bool deleteFromTable(string s) { int firstIdx = hashFunction(s); int secondIdx = lookup(s, firstIdx); SymbolInfoNode *ptr = lookup(s); if(ptr == 0){ // //printf(" Cannot delete since "); //cout << s ; //printf(" doesn't exist.\n"); return false ; } else{ // ptr->printForTable(); //printf(" is deleted from ScopeTableNode #%d at position %d, %d\n", // uniqueID, firstIdx, secondIdx); actuallyDelete(ptr, firstIdx); return true ; } } void actuallyDelete(SymbolInfoNode *pointer, int firstIdx) { SymbolInfoNode *previous = array_of_pointers[firstIdx]; while(previous->getNext() != pointer) previous = previous->getNext(); // //printf("==--->>>==>>PREV is found , printing prev.."); previous->printNode(); // //printf("Printng priv->next.. "); previous->getNext()->printNode(); previous->setNext(pointer->getNext()); pointer->setNext(0); if(pointer) delete pointer ; pointer = 0; } void printTable() { //cout << endl << endl ; //cout << "ScopeTable #" << getID() << endl ; ////printf("Number of Buckets = %d\n", getNumberOfBuckets()); for(int i=0; i<numberOfBuckets; i++) { SymbolInfoNode *ptr = array_of_pointers[i]; //0th is a head of linked list or pointers //cout << i << " :---> " ; while (ptr!=0) { if(ptr->isDummy() == true) ptr = ptr->getNext(); else{ ptr->printForTable(); ptr = ptr->getNext(); } } //cout << endl; } //cout << "------------------*****------------------" << endl ; } string printEverything_2(){ string s = " "; s = s + "ScopeTable #" ; s = s + this->numToStringInST(getID()); s = s + "\n"; ////printf("Number of Buckets = %d\n", getNumberOfBuckets()); for(int i=0; i<numberOfBuckets; i++) { SymbolInfoNode *ptr = array_of_pointers[i]; //0th is a head of linked list or pointers // //cout << i << " :---> " ; while (ptr!=0) { if(ptr->isDummy() == true){ ptr = ptr->getNext(); } else{ s = s + " "; s = s + this->numToStringInST(i); s = s + " :---> " ; s = s + ptr->getEverything_3(); ptr = ptr->getNext(); s = s + "\n"; } } // s = s + "\n"; // //cout << endl; } s = s + "\n"; return s ; } string printNonEmpty() { string s = " "; s = s + "ScopeTable #" ; s = s + this->numToStringInST(getID()); s = s + "\n"; ////printf("Number of Buckets = %d\n", getNumberOfBuckets()); for(int i=0; i<numberOfBuckets; i++) { SymbolInfoNode *ptr = array_of_pointers[i]; //0th is a head of linked list or pointers // //cout << i << " :---> " ; while (ptr!=0) { if(ptr->isDummy() == true){ ptr = ptr->getNext(); } else{ s = s + " "; s = s + this->numToStringInST(i); s = s + " :---> " ; s = s + ptr->getPrintForTable(); ptr = ptr->getNext(); s = s + "\n"; } } // s = s + "\n"; // //cout << endl; } s = s + "\n"; return s ; // s = s + "---------------------******-----------------\n"; // //cout << "------------------*****------------------" << endl ; } void setParent(ScopeTableNode *parent) { // if(parentScope) // delete parentScope ; parentScope = parent ; } ScopeTableNode *getParent() { return parentScope ; } string getPrintNonEmpty() { string s = " "; s = s + "ScopeTable #" ; s = s + this->numToStringInST(getID()); s = s + "\n"; ////printf("Number of Buckets = %d\n", getNumberOfBuckets()); for(int i=0; i<numberOfBuckets; i++) { SymbolInfoNode *ptr = array_of_pointers[i]; //0th is a head of linked list or pointers // //cout << i << " :---> " ; while (ptr!=0) { if(ptr->isDummy() == true){ ptr = ptr->getNext(); } else{ s = s + " "; s = s + this->numToStringInST(i); s = s + " :---> " ; s = s + ptr->getForTabFinally(); ptr = ptr->getNext(); s = s + "\n"; } } // s = s + "\n"; // //cout << endl; } s = s + "\n"; return s ; // s = s + "---------------------******-----------------\n"; // //cout << "------------------*****------------------" << endl ; } }; <file_sep> int main(){ int i, a[10], j; a[2] = 1; a[7] = 0; i = a[2] && a[7]; println(i); // 0 i = a[2] || 0; println(i); // 1 a[2] = 22; a[7] = 31; i = a[2] == a[7]; //0 println(i); i = a[2] >= 22; //1 println(i); i = a[2] != a[7]; //1 println(i); i = a[2] >= 100; //0 println(i); i = a[2] != 4; //1 println(i); } <file_sep>int fun(int a){ //return a; return ( (((a + 1) % 10 ) * 2) + 1); //Always gonna return a num >= 1 } int main(){ int x, a; a = 7; x = fun(a) ; println(x); //Should print 7 since fun(7)=7 , print 17 x = fun(a) < 10; println(x); //Should print 1 since 7 is Actually < 10; .... 19 < 10 is false = 0 } <file_sep> int main(){ int i, c, b ; c = 19; b = 5; int a[10]; a[2] = 7; a[3] = 3; i = -c; println(i); //-19 i = 1; i = !i ; println(i); //-2 i = 0; i = !i; println(i); //-1 i = -a[2]; println(i); //-7 } <file_sep> int main(){ int i, c, b ; c = 19; b = 5; i = c * b; println(i); // 95 i = c/b; println(i); //3 i = c % b; println(i); //4 int a[10]; a[2] = 7; a[3] = 3; i = a[2] * a[3]; println(i); //21 a[4] = a[2] % a[3]; i = a[4]; println(i); //1 a[5] = a[2] / a[3]; i = a[5]; println(i); //2 } <file_sep># Compiler (Simplified) Compiler for a subset of C language > Input: A program in C language (a subset) > Output: Corresponding assembly code (with certain optimizations) ## Highlights - Performed lexical analysis using Flex. - Performed syntactic analysis using Bison. - Implemented certain optimizations while generating assembly code such as: * NOP removal * Efficient usage of temporary variables * Faster multiplication/division by 2 using shift operations. * Removal of consecutive same operations ## Execution Commands #### For script execution ```bash ## Input file: 1505022_Input.txt ## Output file: 1505022.asm ./command.sh ``` #### For step-by-step execution ```bash bison -d -y 1505022.y # To run Bison echo '===>>> 1st step bison -d -y 1505022_Bison.y done\n' g++ -fpermissive -w -c -o y.o y.tab.c echo '===>>> 2nd step g++ -fpermissive -w -c -o y.o y.tab.c done \n' flex 1505022.l # To run flex echo '====>> 3rd step flex 1505022_Flex.l done \n' g++ -fpermissive -w -c -o l.o lex.yy.c echo '====>> 4th step g++ -fpermissive -w -c -o l.o lex.yy.c done\n' g++ -o a.out y.o l.o -lfl -ly echo '====>> 5th step g++ -o a.out y.o l.o -lfl -ly done\n\n\n' ./a.out 1505022_Input.txt # Run the program g++ -o outOpt.out IntermediateCodeStuffs/OptimizerRunner.cpp # Run optimizations ./outOpt.out ``` <file_sep> int main(){ int i, c, b ; c = 7; b = 2; i = c + b; println(i); //9 int a[10]; a[2] =7; a[3] = 4; i = a[2] - a[3]; println(i); //3 i = a[2] - 1; println(i); //6 a[3] = a[2] + a[3]; i = a[3]; println(i); //11 } <file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #define DODO "DODO" #include "../SymbolTable/1505022_SymbolTable.h" using namespace std ; class BisonUtil{ public: ofstream logout; ofstream errout ; ofstream err ; //ofstream debug ; ofstream sem ; //ofstream deb; ofstream arr; string returnFlag = "false" ; int voidCount = -1000; int secondVoidCount = -1000; int numErrors = 0; ArgumentList currentArgumentList; vector<SymbolInfoNode *> list; vector<SymbolInfoNode *> currentFunctionList; string currentFunctionName ; string currentFunctionReturnType; int currentFunctionLine; SymbolInfoNode *firstNode ; SymbolTable *tab ; string currentDataType = "NIL" ; int zeroError = 0; string currentFunctionSymbol; BisonUtil(){ } BisonUtil(SymbolTable *table) { char* errorFile = "Bison_Stuffs/1505022_BisonError.txt"; char* logFile = "Bison_Stuffs/1505022_BisonLog.txt"; errout.open(errorFile); logout.open(logFile); //debug.open("DEBUG_BISON.txt"); arr.open("DebugStuffs/Array_Debug.txt"); sem.open("DebugStuffs/1505022_Semantic.txt"); err.open("DebugStuffs/1505022_ZeroError.txt"); //deb.open("ANOTEHR_DEBUG.txt"); tab = table ; if(tab) { delete tab ; } tab = new SymbolTable(50); //Initially Should enter a new scope.. enterNewScope(); } std::string numToString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } void closeFiles() { errout.close(); logout.close(); err.close(); sem.close(); } void addFirstNode(int flag) { if(flag != 0) return ; if(firstNode) pushToSymbolTable(firstNode); } void printLog(string whatToPrint) { logout << whatToPrint << endl ; //cout << whatToPrint << endl ; voidCount++ ; //logout << "==============>>>>Here, butil.voidCount = " << voidCount << endl << endl ; } void printArrayDebug(string s, SymbolInfoNode *node){ string str = s ; str += "\n"; str += node->getPrintForTable(); arr << str << endl << endl; //cout << str << endl; } void printArrayDebug(string s){ arr << s << endl << endl; //cout << s << endl; } void printDebug(string s) { //debug << s << endl ; //cout << s << endl ; } void printDeb(string s){ //deb << s << endl; //cout << s << endl; } void convertToDataAndPrintLog(SymbolInfoNode *node) { string str = node->getName(); string dataType = node->getDataType(); string type = "ID" ; int len = str.length() ; int lineBegin = node->getLineBegin() ; char *cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); //process in cstr string name = "" ; for(int i=0; i<len; i++){ if(isSafe(cstr[i]) == true) { name += cstr[i] ; }else{ pushToSymbolTable(name, type, dataType, lineBegin); name = "" ; } } pushToSymbolTable(name, type, dataType, lineBegin); delete []cstr ; } void processAndPushToST(SymbolInfoNode *node) { string str = node->getName(); char *cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); int len = str.length(); string temp = ""; for(int i=0; i<len; i++){ if(cstr[i] == ',') { myFunction(temp, node->getLineBegin()); temp = ""; } else{ temp += cstr[i]; } } myFunction(temp, node->getLineBegin()); //printf("\n\n"); } void myFunction(string str, int line) { printLog("Inside myFunction .. str = " + str); char *cstr = new char[str.length() + 1]; strcpy(cstr, str.c_str()); int len = str.length(); string dataType = ""; string name = ""; string type = "ID"; int temp = 0; int pos1 = 0; for(int i=0; i<len; i++){ if(cstr[i] == ' ') continue; else { pos1 = i ; break ; } } for(int i=pos1; i<len; i++){ if(cstr[i] == ' '){ temp = i ; break ; }else{ dataType += (cstr[i] + 'A' - 'a'); } } for(int i=temp; i<len; i++){ if(cstr[i] == ' '){ continue; } name += cstr[i]; } SymbolInfoNode *node = new SymbolInfoNode(name, type, line, dataType); ////printf("==---++===>>>.. "); //node->printNodeB(); pushToSymbolTable(node); } bool isSafe(char c) { int num = 9 ; char toAvoid[] = {',' , '+', '-', '*', '%', '/', '&', '|', ' '}; for(int i=0; i<num; i++){ if(c == toAvoid[i]) return false ; } return true ; } void pushToSymbolTable(SymbolInfoNode *node) { pushToSymbolTable(node->getName(), node->getType(), node->getDataType(), node->getLineBegin(), node->isFunction, node->isArray, node->functionItems, node->arrayItems, node->actualValue, node->symbol, node->code); return ; if(node->getName() == "") { return ; } //printf("\n----------------------------------------------\n"); //printf("Inside pushToSymbolTable , insert to table and printing node ..... "); node->printNodeB(); //tab->Insert(node); string s = tab->printCurrentNonEmpty(); printLog(s); //printf("\n-----------------------------------------------\n"); } bool myProcess(SymbolInfoNode *node){ string name = node->getName(); if(name == ""){ ////printf("name == empty so do nothing..\n"); return false; } char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); for(int i=0; i<name.length(); i++){ if(cstr[i] == ',') return false; } return true ; } void pushUncondition(SymbolInfoNode *n2) { string name = n2->getName(); string type = n2->getType(); string dataType = n2->getDataType(); int lineBegin = n2->getLineBegin(); //tokenType is ID if(name == ""){ //printf("name == empty so do nothing..\n"); return ; } /*char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); for(int i=0; i<name.length(); i++){ if(cstr[i] == ',') return ; }*/ //printf("\n------------------------------------------------\n"); SymbolInfoNode *node = new SymbolInfoNode(name, type, lineBegin, dataType); if(lookup(node) == true) return ; //printf("Inside pushToSymbolTable ... symbol to push is .. "); node->printNodeB(); tab->Insert(node); string s = tab->printCurrentNonEmpty(); printLog(s); //printf("\n-----------------------------------------------------------------\n"); } void pushToSymbolTable(string name, string type ,string dataType, int lineBegin) { string n = ""; for(int i=0; i<name.length(); i++){ if(name[i] == ' ') { continue ; } else{ n += name[i]; } } name = n ; //tokenType is ID string toPrint = ""; if(name == ""){ printDebug("name == empty so do nothing..\n"); return ; } printDebug("\n----------------- <<< INSIDE pushToSymbolTable >>>> -------------------------------\n"); SymbolInfoNode *node = new SymbolInfoNode(name, type, lineBegin, dataType); if(lookup(node) == true) return ; printDebug("Inside pushToSymbolTable ... symbol to push is .. "); node->printNodeB(); tab->Insert(node); string s = tab->printEverything(); printSemantic(s); printDebug("\n--------------------------------<<DONE pushToSymbolTable>>---------------------------------\n"); } void pushToSymbolTable(string name, string type ,string dataType, int lineBegin, bool isFunction, bool isArray, FunctionItems func, ArrayItems arr, string actualValue, string symbol, string code) { string n = ""; for(int i=0; i<name.length(); i++){ if(name[i] == ' ') { continue ; } else{ n += name[i]; } } name = n ; if(name == ""){ //printf("name == empty so do nothing..\n"); return ; } printSemantic("==========++++>>>>> INSERTING IN ST IS Begin !! "); SymbolInfoNode *node = new SymbolInfoNode(name, type, lineBegin, dataType); node->isFunction = isFunction; node->isArray = isArray; node->functionItems = func; node->arrayItems = arr; node->actualValue = actualValue; node->code = code; node->symbol = symbol; SymbolInfoNode *res = tab->LookUp(node->getName()); if(res){ printSemantic("\n\n========>>>lookup(node) " + node->getName() + " is true \n\n"); } else{ printSemantic("\n\n========>>>lookup(node) " + node->getName() + " is false \n\n"); tab->Insert(node); string s = tab->printCurrentNonEmpty(); printSemantic(s); printSemantic("\n---------------------((DONE pushToSymbolTable))--------------------------------------------\n"); } printSemantic("==========++++>>>>> INSERTING IN ST IS DONE !! "); } void checkAndPrint(SymbolInfoNode *node){ SymbolInfoNode *res = tab->LookUp(node->getName()); if(res){ string s = "\nERROR [Variable already declared before] at line "; s += getString(node->getLineBegin()); s += " , Variable name is "; s += res->getName(); s += " , and trying to declare again at line. "; s += res->getLineBegin(); s += "\n"; printError(s); } } void checkUniquenessAndPushST(SymbolInfoNode *node) { SymbolInfoNode *res = tab->searchCurrent(node) ; if(res){ string name = res->getName(); int lineBegin = node->getLineBegin(); printError( "[NOT UNIQUE VAR NAME] : " + name + " already exists at line no " + getString(res->getLineBegin())+ " , trying to declare again at " + getString(lineBegin)); return; } //pushToSymbolTable(node->getName(), node->getType(), node->getDataType(), node->getLineBegin()); pushToSymbolTable(node); } void printLog(string whatToPrint, SymbolInfoNode *node) { int lineNumber = node->getLineBegin(); int lineEnd = node->getLineEnd(); string s = "At Line Number : " ; if(lineNumber == lineEnd) { s += numToString(lineNumber); s += " , "; s += whatToPrint ; s += "\n"; s += node->getName(); //s += "<<==>>Type: " ; //s += node->getDataType(); } else{ //s = "LINE NUMBERS DONT MATCH...\n" ; s += numToString(lineNumber); s += " , "; s += whatToPrint ; s += "\n"; s += node->getName(); } s += "\n"; s += ("Symbol : " + node->symbol); s += "\nCode: \n"; s += node->code; s += "\n"; logout << s ; //cout << s ; voidCount++ ; //logout << "==============>>>>Here, butil.voidCount = " << voidCount << endl << endl ; } void enterNewScope() { string s = tab->enterScope(); printLog(s); } void exitScope() { //printLog("\n==-->>>Calling exitScope()... \n"); /* int currId = tab->getCurrentScopeID(); string x = tab->getAllNonEmpty(); printLog(x); string s = tab->exitScope(); printLog(s); */ //THIS IS ACTUAL //DEBUG int currId = tab->getCurrentScopeID(); string x = tab->printCurrentNonEmpty(); printLog(x); string s = tab->exitScope(); printLog(s); } void push(string name, string type) { tab->Insert(name, type); } void printST() { string s = tab->getAllNonEmpty(); printLog(s); } bool lookup(SymbolInfoNode *n) { return false ; SymbolInfoNode *node = tab->LookUp(n->getName()); if(node != 0){ return true ; } return false ; } std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } void printError(string msg) { numErrors++ ; string s = "\n--------------------------------------\n"; s += getString(numErrors); s += ". "; s += msg ; s += "\n--------------------------------------\n"; errout << s << endl ; //cout << s << endl ; } void printError(string s, bool flag){ errout << s << endl ; } void typeCheck(SymbolInfoNode *node1, SymbolInfoNode *node2) { } bool search(SymbolInfoNode *node) { SymbolInfoNode *n = tab->LookUp(node->getName()); if(n) return true; return false ; } void checkPrintAndPush(SymbolInfoNode *node) { string name = node->getName(); SymbolInfoNode *n = tab->LookUp(node->getName()); //printf("===>>>>Inside checkPrintAndPush ... printing node->getName ..."); //cout << node->getName() << endl ; if(n){ string s = "SEMANTIC ERROR [DOUBLE DEFINITION] " + name + " already exists at line : " + getString(n->getLineBegin()) ; s += "\nTrying to declare " ; s += name ; s += " again at line "; s += getString(node->getLineBegin()); printError(s); return ; } pushToSymbolTable(node); } void printErrorToLog(const char* str, int line, char * token) { string msg(str); string lineNum = getString(line); string tokenName(token); string red = "\n-------------------------------*****-------------------------------\n===>>>>"; string fullMsg = red + "SYNTAX ERROR at line " + lineNum ; fullMsg += " , Error message is : "; fullMsg += msg ; fullMsg += "\nRecent most token is \"" ; fullMsg += token ; fullMsg += "\"" ; fullMsg += "\n-------------------------------*****-------------------------------\n"; printLog(fullMsg); } void declareFunction(SymbolInfoNode *n) { string s = "\n-------------------\n"; n->printNodeB(); s += n->getName(); string name = n->getName(); name = getTrimmedName(name); char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); FunctionItems func ; int i = 0; int nextPos = 0; if(cstr[i] == 'v'){ func.returnType = "VOID" ; nextPos = 4 ; //3 + 1 for extra space } else if(cstr[i] == 'i'){ func.returnType = "INT" ; nextPos = 3 ; //2 + 1 for extra space } else if(cstr[i] == 'f'){ func.returnType = "FLOAT" ; nextPos = 5 ; //4 + 1 for extra space } func.functionName = ""; for(i = nextPos; i<name.length(); i++){ if(cstr[i] == '('){ nextPos = i; break ; } else{ func.functionName += cstr[i]; } } string thisVar = ""; nextPos ++ ; //TO GET RID OF THE FIRST LPAREN / '(' func.numberParameters = 0; if(cstr[i + 1] == ')'){ func.numberParameters = 0; } else{ for(i = nextPos; i<name.length(); i++){ if((cstr[i] == ',') || cstr[i] == ')'){ addToFunction(func, thisVar, n->getLineBegin()); thisVar = ""; func.numberParameters++; } else{ thisVar += cstr[i]; } } } //UPORE PORJONTO RETURN TYPE , AND PARAMETER LIST DONE.. func.lineNumberBegin = n->getLineBegin(); func.lineNumberEnd = n->getLineEnd(); func.declareOrDefine = "DECLARE"; //FUNCTION IS GOING TO BE MADE.. SymbolInfoNode *node = new SymbolInfoNode(func.functionName, func.returnType); node->functionItems = func; node->setDataType(func.returnType) ; node->isFunction = true ; node->setLineBegin(func.lineNumberBegin); node->setLineEnd(func.lineNumberEnd); //FUNCTION IS MADE.. /*string x = node->functionItems.getFunction(); printDebug(x); string x2 = node->getPrintForTable(); printDebug(x2); */ //PUSH TO SYMBOL TABLE checkPrintAndPush(node); //printf("\n-------------------------------------------------------\n"); } void defineFunction(SymbolInfoNode *n) { string s = "\n-------------------------------------------------\nInside defineFunction..printing n->getName.."; //n->printNodeB(); s += n->getName(); printSemantic(s); string name = n->getName(); //name = getTrimmedName(name); char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); FunctionItems func ; int i = 0; int nextPos = 0; for(int i=0; i<name.length(); i++){ if(name[i] == ' ') continue; else{ nextPos = i; break ; } } i = nextPos ; if(cstr[i] == 'v'){ func.returnType = "VOID" ; nextPos += 4 ; //3 + 1 for extra space } else if(cstr[i] == 'i'){ func.returnType = "INT" ; nextPos += 3 ; //2 + 1 for extra space } else if(cstr[i] == 'f'){ func.returnType = "FLOAT" ; nextPos += 5 ; //4 + 1 for extra space } func.functionName = ""; for(i = nextPos; i<name.length(); i++){ if(cstr[i] == '('){ nextPos = i; break ; } else{ func.functionName += cstr[i]; } } string thisVar = ""; nextPos ++ ; //TO GET RID OF THE FIRST LPAREN / '(' func.numberParameters = 0; if(cstr[i + 1] == ')'){ func.numberParameters = 0; } else{ for(i = nextPos; i<name.length(); i++){ if(cstr[i] == ')'){ func.numberParameters++; addToFunction(func, thisVar, n->getLineBegin()); break ; } else if((cstr[i] == ',')){ addToFunction(func, thisVar, n->getLineBegin()); thisVar = ""; func.numberParameters++; } else{ thisVar += cstr[i]; } } } //UPORE PORJONTO RETURN TYPE , AND PARAMETER LIST DONE.. //func.lineNumberBegin = n->getLineBegin(); func.lineNumberBegin = currentFunctionLine ; func.lineNumberEnd = n->getLineEnd(); func.declareOrDefine = "DEFINE"; //FUNCTION IS GOING TO BE MADE.. SymbolInfoNode *node = new SymbolInfoNode(func.functionName, func.returnType); node->functionItems = func; node->setDataType(func.returnType) ; node->isFunction = true ; node->setLineBegin(func.lineNumberBegin); node->setLineEnd(func.lineNumberEnd); node->symbol = "res_" + getTrimmedName(func.functionName); //FUNCTION IS MADE.. printSemantic("INSIDE defineFunction ... \n"); string x = node->functionItems.getFunction(); printSemantic(x); string x2 = node->getPrintForTable(); printSemantic(x2); printSemantic("===>>IMMEDIATELY BEFORE checkForDeclareAndPush .... \n"); //CHECK FOR DECLARATION .. OTHERWISE PUSH TO SYMBOL TABLE checkForDeclareAndPush(node); //checkPrintAndPush(node); printSemantic("\n--------------------[[ DONE WITH defineFunction ]] -----------------------------------\n"); } void addToFunction(FunctionItems &fun, string var, int lineBegin) { //string s = "\n-------------------------************------------------------\n"; string s = ""; s += "Inside addToFunction , var ="; s += var ; s += "\n" ; printDebug(s); int start = 0; for(int i=0; i<var.length(); i++){ if(var[i] == ' '){ start ++ ; }else{ start = i; break ; } } char *str = new char[var.length() + 1]; strcpy(str, var.c_str()); int i = start; int nextPos = start; string dataType = ""; bool isValid = false ; if(var[i] == 'f'){ dataType = "FLOAT"; nextPos += 5; isValid = true ; }else if(var[i] == 'i'){ dataType = "INT"; nextPos += 3; isValid = true ; } if(!isValid){ printDebug("Unidentified data type .. \n"); } string name = ""; for(i = nextPos; i<var.length(); i++){ if(var[i] == ' ') continue; name += var[i]; } //printDebug("Name : " + name + " , dataType = " + dataType + "\n"); Variable variable; variable.makeVariable(name, dataType, lineBegin); fun.addFunctionItem(variable); //s += "\n-------------------------************------------------------\n"; } void checkForDeclareAndPush(SymbolInfoNode *node) { printSemantic("===>>>>Inside checkForDeclareAndPush ... printing node->getName ..."); string name = node->getName(); name = getTrimmedName(name); printSemantic("node->name = " + name); SymbolInfoNode *res = tab->LookUp(name); if(res){ printSemantic("res exists in symbol table!!\n"); if(res->isFunction == false){ string s = "SEMANTIC ERROR [DOUBLE DEFINITION] " + name + " already exists at line : " ; s += getString(res->getLineBegin()); s += "\nTrying to declare " ; s += name ; s += " again at line "; s += getString(node->getLineBegin()); printSemantic(s); printError(s); return ; } else{ printSemantic("Name exists but is not function ... Go for matchWithDeclareAndPush(node, res)"); matchWithDeclareAndPush(node, res); return; } }else{ printSemantic("Name doesnot exist so .. Go for pushToSymbolTable( ... )"); pushToSymbolTable(node->getName(), node->getType(), node->getDataType(), node->getLineBegin(), node->isFunction, node->isArray, node->functionItems, node->arrayItems, node->actualValue, node->symbol, node->code); } printSemantic("===>>>>AFTER checkForDeclareAndPush Printing the node... "); if(node){ printSemantic(node->getPrintForTable()); if(node->isFunction){ printSemantic(node->functionItems.getFunction()); } } } void matchWithDeclareAndPush(SymbolInfoNode *definition, SymbolInfoNode *declaration) { FunctionItems f1 = definition->functionItems ; FunctionItems f2 = declaration->functionItems; string s = f1.equals(f2); if(s == "Matched"){ changeFunction(definition, declaration); printDebug("CHANGED .. printing ST "); string s = tab->printCurrentNonEmpty(); printDebug(s); s = declaration->functionItems.getFunction(); printDebug(s); } else{ //printError("SEMANTIC ERROR [function declaration and definition not match] .. func name declaration is " // + f1.functionName + " , definition is " + f2.functionName + "\nError is : " + s); printError("SEMANTIC ERROR at line. " + definition->getString(definition->getLineBegin()) + " : function with name " + f2.functionName + ", declaration and definition don't match\n" + s); return ; } } void changeFunction(SymbolInfoNode *definition, SymbolInfoNode *declaration){ for(int i=0; i<(int)declaration->functionItems.list.size(); i++){ declaration->functionItems.list[i].name = definition->functionItems.list[i].name; } declaration->functionItems.declareOrDefine = definition->functionItems.declareOrDefine; declaration->functionItems.lineNumberBegin = definition->functionItems.lineNumberBegin; declaration->functionItems.lineNumberEnd = definition->functionItems.lineNumberEnd; } string getTrimmedName(string s) { string str = ""; for(int i=0; i<s.length(); i++){ if(s[i] == ' ') continue ; str += s[i]; } return str ; } void printDeb(string str, SymbolInfoNode *node){ string s = "\n==========>>Inside printDeb <<=========\n"; s += str ; s += "\nPRINTING NODE NOW ..\n"; s += node->getPrintForTable(); if(node->isArray){ s += node->arrayItems.getArrayItem(); } if(node->isFunction){ s += node->functionItems.getFunction(); } s += "\nNODE NAME :"; s += node->getName(); s += "\n<<<<<<<<<<< DONE >>>>>>>>>>>>\n"; printDeb(s); } void printSemantic(string str, SymbolInfoNode *node){ string s = "\n"; s += str ; s += "\nPRINTING NODE NOW ..\n"; s += node->getPrintForTable(); if(node->isArray){ s += node->arrayItems.getArrayItem(); } if(node->isFunction){ s += node->functionItems.getFunction(); } s += "\nNODE NAME :"; s += node->getName(); s += "\n"; printSemantic(s); } void printDebug(string str, SymbolInfoNode *node){ string s = "\n======================************INSIDE printDebug(node)*****************=======================\n"; s += str ; s += "\nPRINTING NODE NOW ..\n"; s += node->getPrintForTable(); if(node->isArray){ s += node->arrayItems.getArrayItem(); } if(node->isFunction){ s += node->functionItems.getFunction(); } s += "\nNODE NAME :"; s += node->getName(); s += "\n=====================================*****************************==============================================\n"; printDebug(s); } pushUndeclared(SymbolInfoNode *node){ list.push_back(node); } printAllUndeclaredVariables(){ string s = "\n---------------------------------Inside printAllUndeclaredVariables() ....-----------------\n"; for(int i=0; i<(int)list.size(); i++){ SymbolInfoNode *node = list[i]; string x = node->getPrintForTable(); s += x; } s += "\n----------------------------------------------------------------------------------------------\n"; printDebug(s); } int getSize(string s){ // object from the class stringstream stringstream geek(s); // The object has the value 12345 and stream // it to the integer x int x = 0; geek >> x; return x ; } int getSize(SymbolInfoNode *node){ string s = node->getName(); return getSize(s); } void pushForFunction(SymbolInfoNode *node){ //printDebug("\n===================Inside pushForFunction(node) .. node =" + node->getPrintForTable() + "\n"); string name = node->getName(); for(int i=0; i<(int)currentFunctionList.size(); i++){ if(currentFunctionList[i]->getName() == name) return ; } currentFunctionList.push_back(node); } SymbolInfoNode* getInCurrentFunction(SymbolInfoNode *node){ return getInCurrentFunction(node->getName()); } SymbolInfoNode* getInCurrentFunction(string name){ for(int i=0; i<(int)currentFunctionList.size(); i++){ if(currentFunctionList[i]->getName() == name){ return currentFunctionList[i]; } } return 0; } void printAllCurrentFunctionVariables(){ string s = "\n=========================<<<<In printAllCurrentFunctionVariables()>>>>>==========================\n"; for(int i=0; i<(int)currentFunctionList.size(); i++){ s += currentFunctionList[i]->getPrintForTable(); } s += "\n====================================<<<<<<<<<<<<<<<<<DONE>>>>>>>>>>>>>>====================================\n"; printDebug(s); } void removeAllCurrentFunVar() { currentFunctionList.clear(); //printDebug("=============>>>After removeAllCurrentFunVar ... "); //printAllCurrentFunctionVariables(); } void removeFromCurrentFunction(SymbolInfoNode *node){ printDebug("\n======Inside removeFromCurrentFunction .. node->getName = " + node->getName() + "\n"); string name = node->getName(); char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); int i = 0; //Start with '('; string thisVar = ""; int nextPos = 1 ; if(cstr[i + 1] == ')'){ return ; } else{ for(i = nextPos; i<name.length(); i++){ if((cstr[i] == ',') || cstr[i] == ')'){ removeFromFunction(thisVar); thisVar = ""; } else{ thisVar += cstr[i]; } } } } void removeFromFunction(string var){ printDebug("++++++==>>> Inside removeFromFunction(" + var + ")\n"); int start = 0; for(int i=0; i<var.length(); i++){ if(var[i] == ' '){ start ++ ; }else{ start = i; break ; } } char *str = new char[var.length() + 1]; strcpy(str, var.c_str()); int i = start; int nextPos = start; string dataType = ""; bool isValid = false ; if(var[i] == 'f'){ dataType = "FLOAT"; nextPos += 5; isValid = true ; }else if(var[i] == 'i'){ dataType = "INT"; nextPos += 3; isValid = true ; } string name = ""; for(i = nextPos; i<var.length(); i++){ if(var[i] == ' ') continue; name += var[i]; } for(int i=0; i<(int)currentFunctionList.size(); i++){ if(currentFunctionList[i]->getName() == name){ currentFunctionList.erase(currentFunctionList.begin() + i); } } } bool doesExist(SymbolInfoNode *node){ string name = node->getName(); printDebug("\n==>>> INSIDE doesExist(node) ===========================\n"); string s = node->getPrintForTable(); printDebug(s); int line = node->getLineBegin(); string dataType = node->getType(); bool isArray = node->isArray ; int i = 0; int nextPos = 0; string str = name ; for(i=0; i<name.length(); i++){ if(str[i] == ' ') continue; else{ nextPos = i; break ; } } if(dataType == "INT"){ nextPos += 3; } else if(dataType == "FLOAT"){ nextPos += 5; } string var = "" ; for(i=nextPos; i<str.length(); i++){ if((str[i] == ',') || (str[i] == ';')){ checkAndPush(var, dataType, isArray, line ); var = ""; break; } else{ var += str[i]; } } checkAndPush(var, dataType, isArray, line ); //printDebug("\n========================================<<<<< DONE >>>>>>=====================================\n"); return false; } void checkAndPush(string id, string type, bool isArray, int line ){ if(id == "") return ; printDebug("==--===>>Inside checkAndPush, id =" + id + " , type =" + type); string name = "" ; for(int i=0; i<id.length(); i++){ if(id[i] == '[') break ; name += id[i]; } name = getTrimmedName(name); SymbolInfoNode *res = tab->LookUp(name); bool isFunction = false ; //FUNCTION CHECK if(res){ isFunction = res->isFunction; if(isFunction == true){ printError("SEMANTIC ERROR[Variable and Function Names match] at line." + getString(line) + " , name is : \"" + res->getName() + "\" , function is at line " + getString(res->getLineBegin()) + " and ID is at line. " + getString(line)); return ; } } if(name == currentFunctionName){ printError("SEMANTIC ERROR [Id and Function Names match] and ID exists at line. " + getString(line) + " and function defined or declared at line " + getString(currentFunctionLine)); return ; } //FUNCTION CHECK DONE //PARAMETER CHECK printAllCurrentFunctionVariables(); SymbolInfoNode *node ; string varName ; for(int i=0; i<(int)currentFunctionList.size(); i++){ node = currentFunctionList[i]; varName = node->getName(); printDebug("+++++================>>>varName =" + varName + " , and name =" + name); if(varName == name){ printError("SEMANTIC ERROR[MULTIPLE DECLARATION] ... " + name + " is declared once as PARAMETER also."); return ; } } //PARAMETER CHECK DONE /*SymbolInfoNode *newNode = new SymbolInfoNode(id, "ID", line, type); newNode->isArray = isArray; newNode->isFunction = false; pushToSymbolTable(newNode); */ } void printError(int x){ errout << getString(x); } bool isValidNameOfID(string id ){ int len = id.length(); for(int i=0; i<len; i++){ if((id[i] == '{') ||(id[i] == '}') ||(id[i] == '(') ||(id[i] == ')') ||(id[i] == '[') ||(id[i] == ']') ||(id[i] == '+') ||(id[i] == '-')||(id[i] == '/')||(id[i] == '?')||(id[i] == '<')||(id[i] == '>')||(id[i] == '=') || (id[i] == '%')||(id[i] == '|') || (id[i] == '&')){ return false; } } char charArr[11] = {'0','1','2','3','4','5','6','7','8','9'}; for(int i=0; i<11; i++){ if(id[0] == charArr[i]) return false; } return true ; } SymbolInfoNode* searchForUndeclaredID(SymbolInfoNode *node2 ){ //EDITED JUST NOW.. if(isValidNameOfID(node2->getName()) == false) return node2; string id = node2->getName(); string type = node2->getType(); bool isArray = node2->isArray; int line = node2->getLineBegin(); SymbolInfoNode *noNode = new SymbolInfoNode(node2->getName(), node2->getType(), node2->getLineBegin(), node2->dataType); //noNode->actualValue = node2->actualValue; noNode->makeNode(node2); if(id == "") return noNode; string name = "" ; for(int i=0; i<id.length(); i++){ if(id[i] == '[') break ; name += id[i]; } name = getTrimmedName(name); SymbolInfoNode *res = tab->LookUp(name); bool isFunction = false ; printSemantic("==>>Inside searchForUndeclaredID, BisonUtil Line 1127. CHECKING FOR Node:\n" + node2->getPrintForTable()); if(res){ if(res->getName() == currentFunctionName){ //Check for current function printError("SEMANTIC Error , Variable name and function names: \"" + currentFunctionName + "\" are same " + " Function was at line . " + getString(currentFunctionLine) + " and var at " + getString(res->getLineBegin())); printSemantic("MATCHES current func name."); return noNode; }else if(res->isFunction == true){ //Check for is it a function printError("SEMANTIC Error, Function " + res->getName() + " used without brackets. at line " + getString(node2->getLineBegin())); printSemantic("Matches isFunction == true"); return noNode; }else if(res->isArray == true){ //Check for is it an array printError("SEMANTIC Error, Array " + res->getName() + " is used without third brackets at line. " + getString(node2->getLineBegin())); printSemantic("Matches isArray == true"); return noNode; } else{ //No errors. printSemantic("NO ERRORS.."); return res; } } else{ //Check for parameters of function. for(int i=0; i<(int)currentFunctionList.size(); i++){ SymbolInfoNode *itr = currentFunctionList[i]; if(itr->getName() == name){ printSemantic("Matches param list. ", itr); return itr; } } //UNDECLARED printSemantic("DOES NOT MATCH ANYTHING HENCE ERROR."); printError("SEMANTIC Error at line. " + getString(line) + " Variable " + name + " is UNDECLARED."); return noNode; } return noNode ; } void printSemantic(string s) { sem << s << endl ; cout << s << endl ; } void printLog(string s, bool flag){ //logout << s << endl; ////cout << s << endl ; } void printZero(string s, bool flag){ zeroError++; string str = getString(zeroError); str += ") "; str += s ; if(flag){ err << str << endl ; }else{ err << s << endl ; } if(flag){ //cout << s << endl; } } void printZero(string s){ printZero(s, true); } }; // pushToSymbolTable(node->getName(), node->getType(), node->getDataType(), node->getLineBegin(), // node->isFunction, node->isArray, node->functionItems, node->arrayItems); /* char *cstr = new char[name.length() + 1]; strcpy(cstr, name.c_str()); for(int i=0; i<name.length(); i++){ if(cstr[i] == ',') return false; } */ /* if(var[i] == 'i'){ if(var[i+1] == 'n'){ if(var[i+2] == 't'){ dataType = "INT"; nextPos = 3; } } }else if(var[i] == 'f'){ if(var[i+1] == 'l'){ if(var[i+2] == 'o'){ if(var[i+3] == 'a'){ if(var[i+4] == 't'){ dataType = "FLOAT"; nextPos = 5; } } } } } */<file_sep>clear clear clear clear bison -d -y 1505022.y echo '===>>> 1st step bison -d -y 1505022_Bison.y done\n' g++ -fpermissive -w -c -o y.o y.tab.c echo '===>>> 2nd step g++ -fpermissive -w -c -o y.o y.tab.c done \n' flex 1505022.l echo '====>> 3rd step flex 1505022_Flex.l done \n' g++ -fpermissive -w -c -o l.o lex.yy.c echo '====>> 4th step g++ -fpermissive -w -c -o l.o lex.yy.c done\n' g++ -o a.out y.o l.o -lfl -ly echo '====>> 5th step g++ -o a.out y.o l.o -lfl -ly done\n\n\n' ./a.out 1505022_Input.txt g++ -o outOpt.out IntermediateCodeStuffs/OptimizerRunner.cpp ./outOpt.out #echo '=>Trying to execute Optmizer.l\n' #flex -o output2.cpp IntermediateCodeStuffs/OptimizedCodes/1505022_Optimizer.l #echo '=>1st Step Done\n' #g++ output2.cpp -lfl -o out2.out #echo '=>2nd Step Done\n' #./out2.out IntermediateCodeStuffs/ICode.asm #echo '=>3rd Step Done\n' #g++ -o output foo.c<file_sep>int main(){ int a,b,i; b=0; for(i=0;i<4;i++){ a=3; while(a--){ b++; } } println(a); //-1 amar ashe 0 println(b); //12 amar ashe 8 println(i); //4 }<file_sep>int f2(int); int f3(int); int f1(int a){ if(a<10){ return f2(a); //return 2*a }else{ return f3(a); //return 3*a } } int main(){ int a[10]; int i ; i = 0; while(i < 10){ a[i] = i; i++; } int x, y; x = f1(a[0]); //a[0] = 0 y = f2(a[1]); //a[1] = 1 println(x); println(y); } int f2(int x){ if(x != 0){ return 2*x; }else{ return 2; } } int f3(int b){ if(b != 0){ return 3*b; }else{ return 3; } } <file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> #include "1505022_ScopeTable.h" using namespace std ; //int bucketSize = 0 ; //int current_scope_number = 1; class SymbolTable { private: int number_of_buckets_for_all; int counter_scopeTable ; // ScopeTableNode *initialScopeTableNode ; ///same as head ScopeTableNode *currentScopeTable ; ///This pointer changes with new scope or exit scope public: int global_scope = 1; int getCurrentScopeID(){ return currentScopeTable->getID(); } SymbolTable(int n) { number_of_buckets_for_all = n ; //Start with 50 buckets currentScopeTable = 0 ; counter_scopeTable = 1 ; } ~SymbolTable() { if(currentScopeTable) delete currentScopeTable ; currentScopeTable = 0 ; } string enterScope() { // ScopeTableNode *tab = new ScopeTableNode(number_of_buckets_for_all, counter_scopeTable); ScopeTableNode *tab = new ScopeTableNode(number_of_buckets_for_all, global_scope); global_scope++ ; if(currentScopeTable == 0){ /// or we couldve used if(counter == 0) //then initialize the initialScopeTable currentScopeTable = tab ; currentScopeTable->setParent(0); } else{ ///create a new scope table and insert parent pointer accordingly tab->setParent(currentScopeTable) ; currentScopeTable = tab ; } counter_scopeTable ++ ; ////cout << "New Scope Table with id = " << currentScopeTable->getID() << " is created.\n" ; string s = "\n\tNew Scope Table with id = " ; s += numToString(currentScopeTable->getID()); s += " is created. \n"; return s ; // //printf("New Scope Table with id = %d is created.\n", currentScopeTable->getID()); } string exitScope() { ///Removes current scope table ScopeTableNode *curr = currentScopeTable ; ///If empty if(curr == 0){ //cout << "\tSymbol Table is empty.\n"; return "\tEmpty Symbol Table\n"; } ///This is the head else if(curr->getParent() == 0){ ////cout << "\tScope Table with id = " << curr->getID() << " is removed.\n" ; curr->setParent(0); int currentScopeID = curr->getID(); if(curr) delete curr ; //curr = 0 ; currentScopeTable = 0 ; //---**EDITED HERE**---- nicher ta commentout chilo nah counter_scopeTable--; string s = "\n\tScope Table with id = " ; s+= numToString(currentScopeID) ; s += " is removed.\n"; // //printf("RETURNING FROM <ELSE-IF> in EXIT_SCOPE FUNC\n"); return s; } //NORMAL CASE .. currentScopeTable = curr->getParent() ; // //cout << "\tScope Table with id = " << curr->getID() << " is removed.\n"; // //printf("\tScope Table with id = %d is removed.\n", curr->getID()); int c_id = curr->getID(); curr->setParent(0); if(curr) delete curr ; curr = 0; counter_scopeTable-- ; string s = "\n\tScope Table with id = " ; s+= numToString(c_id) ; s += " is removed.\n"; return s; } std::string numToString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } SymbolInfoNode *searchCurrent(SymbolInfoNode *n) { SymbolInfoNode *node = 0 ; ScopeTableNode *itr = currentScopeTable ; string name = n->getName(); if(name == "") return 0 ; node = itr->lookup(name); int pos = itr->lookup(name, itr->hashFunction(name)); return node ; } bool Insert(SymbolInfoNode *n) { printf("SymbolTable.INSERT is BEGINNNING!!!\n"); if(currentScopeTable == 0){ //cout << "Can't Insert in Empty Symbol Table\n"; // //printf("Can't Insert since Symbol Table is empty\n"); return false ; } if(!n){ printf("Line 154.... n is not present !!"); return; } //SymbolInfoNode *node = this->LookUp(n->getName()); if(!n){ printf("Inside SymbolTable.INSERT ... parameter er node doesnot exist! \n"); return false ; } SymbolInfoNode *node = currentScopeTable->lookup(n->getName()); if(node != 0){ node->printForTable() ;//cout << " already exists in the current ScopeTable\n" ; return false ; } //bool flag = currentScopeTable->insert(symbol_name, symbol_type); SymbolInfoNode *newNode = new SymbolInfoNode(n->getName(), n->getType()); newNode->dataType = n->dataType; newNode->actualValue = n->actualValue; newNode->isArray = n->isArray; newNode->isFunction = n->isFunction; newNode->symbol = n->symbol; newNode->code = n->code ; //newNode->functionItems.list.size() = n->functionItems.list.size(); newNode->line_number_begin = n->line_number_begin; newNode->line_number_end = n->line_number_end; if(newNode->isArray && n->isArray){ newNode->arrayItems.changeArray(n->arrayItems); } if(newNode->isFunction && n->isFunction){ newNode->functionItems.changeFunction(n->functionItems); } printf("SymbolTable.INSERT is MIDDLE!!!\n"); currentScopeTable->insert(newNode, currentScopeTable->hashFunction(newNode->getName())); string symbol_name = newNode->getName(); int pos = currentScopeTable->lookup(symbol_name, currentScopeTable->hashFunction(symbol_name)); //cout << "\tInserted in ScopeTable #" << currentScopeTable->getID() << " at position " << //currentScopeTable->hashFunction(symbol_name) << " , " << pos << endl ; // //printf("\tInserted in ScopeTable #%d at position %d, %d\n", // currentScopeTable->getID(), currentScopeTable->hashFunction(symbol_name), pos); printf("SymbolTable.INSERT is DONE!!!\n"); return true ; } bool Insert(string symbol_name, string symbol_type, string dataType, int lineBeg, bool isArray, bool isFunction, string actualValue, FunctionItems f, ArrayItems a) { if(currentScopeTable == 0){ //cout << "Can't Insert in Empty Symbol Table\n"; // //printf("Can't Insert since Symbol Table is empty\n"); return false ; } SymbolInfoNode *node = currentScopeTable->lookup(symbol_name); if(node != 0){ node->printForTable() ;//cout << " already exists in the current ScopeTable\n" ; return false ; } bool flag = currentScopeTable->insert(symbol_name, symbol_type, dataType, lineBeg, isArray, isFunction, actualValue, f, a); int pos = currentScopeTable->lookup(symbol_name, currentScopeTable->hashFunction(symbol_name)); ////cout << "\tInserted in ScopeTable #" << currentScopeTable->getID() << " at position " << //currentScopeTable->hashFunction(symbol_name) << " , " << pos << endl ; // //printf("\tInserted in ScopeTable #%d at position %d, %d\n", // currentScopeTable->getID(), currentScopeTable->hashFunction(symbol_name), pos); return true ; } bool Insert(string symbol_name, string symbol_type) { if(currentScopeTable == 0){ //cout << "Can't Insert in Empty Symbol Table\n"; // //printf("Can't Insert since Symbol Table is empty\n"); return false ; } SymbolInfoNode *node = currentScopeTable->lookup(symbol_name); if(node != 0){ node->printForTable() ;//cout << " already exists in the current ScopeTable\n" ; return false ; } bool flag = currentScopeTable->insert(symbol_name, symbol_type); int pos = currentScopeTable->lookup(symbol_name, currentScopeTable->hashFunction(symbol_name)); ////cout << "\tInserted in ScopeTable #" << currentScopeTable->getID() << " at position " << //currentScopeTable->hashFunction(symbol_name) << " , " << pos << endl ; // //printf("\tInserted in ScopeTable #%d at position %d, %d\n", // currentScopeTable->getID(), currentScopeTable->hashFunction(symbol_name), pos); return true ; } bool Remove(string symbolName) { if(currentScopeTable == 0){ //cout << "SymbolTable is empty." << endl ; return false ; } int pos = currentScopeTable->lookup(symbolName, currentScopeTable->hashFunction(symbolName)); SymbolInfoNode *node = currentScopeTable->lookup(symbolName); if(node == 0){ //cout << "\tNot present in SymbolTable" << endl ; return false ; } //cout << "\t" << symbolName << " " ; //cout << "is present in ScopeTable #" << currentScopeTable->getID() << " at position " << currentScopeTable->hashFunction(symbolName) //<< " , " << pos << endl ; // //printf("is present in ScopeTable #%d at position %d, %d\n", currentScopeTable->getID(), // currentScopeTable->hashFunction(symbolName), pos); ///Function call.. //currentScopeTable->deleteFromTable(symbolName); // //printf("Deleted entry at %d, %d from current ScopeTable\n", currentScopeTable->hashFunction(symbolName), pos); //cout << "Deleted entry at " << currentScopeTable->hashFunction(symbolName) << ", " << pos << " from current ScopeTable\n"; return true ; } SymbolInfoNode *LookUp(string name) { SymbolInfoNode *node = 0 ; ScopeTableNode *itr = currentScopeTable ; while(itr != 0) { node = itr->lookup(name); if(node != 0){ // //printf("Found at ScopeTable %d") int pos = itr->lookup(name, itr->hashFunction(name)); // //printf("\tFound in ScopeTable %d at position %d, %d\n", itr->getID(), itr->hashFunction(name), pos); //cout << "\tFound in ScopeTable " << itr->getID() << " at position " << itr->hashFunction(name) << " , " << pos << endl ; return node ; } itr = itr->getParent(); } // //printf("\tDoes not exist in the Symbol Table\n"); //cout << "\tDoes not exist in the Symbol Table\n" << endl ; return 0 ; } void printCurrent() { if(currentScopeTable == 0){ // //printf("Empty SymbolTable\n"); //cout << "Empty SymbolTable" << endl ; return ; } currentScopeTable ->printTable(); } void printAll() { if(currentScopeTable == 0){ // //printf("Empty SymbolTable\n"); //cout << "Empty SymbolTable" << endl ; return ; } ScopeTableNode *itr = currentScopeTable; while(itr != 0){ itr->printTable(); itr = itr->getParent(); } } string printCurrentNonEmpty() { string s = ""; if(currentScopeTable == 0){ s = "Empty SymbolTable\n"; } else{ s = currentScopeTable->printNonEmpty(); } return s ; } string printEverything(){ string s = ""; if(currentScopeTable == 0){ s = "Empty SymbolTable\n"; } else{ s = currentScopeTable->printEverything_2(); } return s ; } string printAllNonEmpty() { string s = "" ; if(currentScopeTable == 0){ s = "Empty SymbolTable\n"; return s ; } ScopeTableNode *itr = currentScopeTable; while(itr != 0){ s += itr->printNonEmpty(); itr = itr->getParent(); } return s ; } string getAllNonEmpty(){ string s = "" ; if(currentScopeTable == 0){ s = "Empty SymbolTable\n"; return s ; } ScopeTableNode *itr = currentScopeTable; while(itr != 0){ s += itr->getPrintNonEmpty(); itr = itr->getParent(); } return s ; } }; /// ------------------*****------------------------------------*****------------------ /* vector<string> splitString(const string& a, char delim) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(a); while (std::getline(tokenStream, token, delim)) { tokens.push_back(token); } return tokens; } void printArray(string arr[], int n) { //cout << endl ; for(int i=0; i<n; i++) { //cout << arr[i] << " " ; } //cout << endl << endl ; } void printArray(string s) { //cout << endl ; //cout << s << endl << endl ; } void printArray(char c[], int len) { //cout << "LENGTH = " << len << endl ; for(int i=0; i<len; i++){ //cout << c[i] << " , " ; } //cout << endl ; } */<file_sep>#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<fstream> #include <set> #include <iterator> #include<vector> #include<algorithm> #include<istream> #include <sstream> #include<cstring> using namespace std ; class PairItems{ public: int index; string value; PairItems(){ index = -1; value = "NOT_YET_ASSIGNED"; } std::string getString ( int Number ) { std::ostringstream ss; ss << Number; return ss.str(); } PairItems(int i, string v){ index = i; value = v; } string getString(){ string s = ""; s += "<<< Index = " ; s += getString(index) ; s += " , value = "; s += value; s += " >>>"; s += " "; return s; } };
b7bdeac364697d4cda6000b19918ffe2231c9856
[ "Markdown", "C", "C++", "Shell" ]
26
C++
Mahim1997/Compiler-Simplified
3da77f3e8affe5024c3c6d210eded884ea950b51
192e1ebf4347c0078685f08c8e1817d6306dab0d
refs/heads/main
<repo_name>Ritwika101/DSA-Mini-Project<file_sep>/README.md # DSA-Mini-Project Design a program to create and display a priority queue using a linked list. <br> Program Time and Space Complexity<br> Time complexity for function enqueue() - O(n)<br> Time complexity for function display() - O(n)<br> <file_sep>/Code.c #include <stdio.h> #include <stdlib.h> struct node { int info, prn; struct node *next; } *front = NULL, *rear = NULL; void enqueue(int item, int pr) //function to insert an element { struct node *p, *temp = (struct node *)malloc(sizeof(struct node)); //creating node to be inserted temp -> info = item; temp -> prn = pr; temp -> next = NULL; if(rear == NULL) //creating the first node { front = temp; rear = temp; } else { p = front; if((p -> prn) > (temp -> prn)) //inserting the node at front { temp -> next = front; front = temp; return; } while(((p -> next) != NULL) && ((p -> next -> prn) <= (temp -> prn))) p = p -> next; //finding out the position where the node is to inserted if((p -> next) == NULL) //inserting the node at rear { p -> next = temp; rear = p -> next; } else //inserting the node in between other nodes { temp -> next = p -> next; p -> next = temp; } } } void display() //function to display the elements { printf("Priority Queue: "); struct node *p = front; if(p==NULL) //underflow condition { printf("Queue is empty.\n"); return; } while(p!=NULL) //displaying elements { printf("%d ", p -> info); p = p -> next; } printf("\n"); } void main() { int n, val, p, ch; printf("1. Create\n2. Display\n3. Exit\n"); while(1) { printf("\nEnter choice: "); scanf("%d", &ch); switch(ch) { case 1: printf("Enter the value: "); //inserting an element scanf("%d", &val); printf("Enter its priority: "); scanf("%d", &p); if(p<1) //checking for invalid priority { printf("Priority should be greater than or equal to 1.\n"); break; } enqueue(val, p); break; case 2: display(); //displaying elements break; case 3: return; //terminating the program } } }
ed7fdd8e07ac3f22022efabe23ba567635ec3c4c
[ "Markdown", "C" ]
2
Markdown
Ritwika101/DSA-Mini-Project
23de6bb3365b1ba601e1abe29e12e57b1e70e74e
72ee798f71996e05b2fc4f7cf87c05658c2fedf3
refs/heads/main
<file_sep># Calculator-in-Shell Implemented a calculator using Linux shell script, with the following four operators: 1 - Add (a) 2 - Subtract (s) 3 - Multiply (m) 4 - Divide (d) Only two operands and one operator will be allowed. Each operand can only be a number between 1-100. The data is first verified to be within the range and valid, meaning no alphabets or any other character is given as input. <file_sep> echo -n "Enter first number: " read num1 while [ $num1 -lt 1 -o $num1 -gt 100 ] do echo "Number not in range. Please enter again: " read num1 done echo -n "Enter operator (a,s,m,d): " read op while [ $op != 'a' -a $op != 's' -a $op != 'm' -a $op != 'd' ] do echo "Operator not valid. Please enter again: " read op done echo -n "Enter second number: " read num2 while [ $num2 -lt 1 -o $num2 -gt 100 ] do echo "Number not in range. Please enter again: " read num2 done case $op in 'a') ans=$(( $num1+$num2 )) ;; 's') ans=$(( $num1-$num2 )) ;; 'm') ans=$(( $num1*$num2 )) ;; 'd') ans=$(( $num1/$num2 )) ;; esac echo "Result: $ans"
9a1d4fc6ea66f91509f51f076a0ea3ca893406e7
[ "Markdown", "Shell" ]
2
Markdown
SanaBasharat/Calculator-in-Shell
0349db6909a4910b2b33d36f21b42e252ec81161
ef4979932ee33239703351c375ab6d0249bdfac8
refs/heads/main
<file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require(PRODUCT_DIR . 'libs/product.lib'); require_once(SMARTY_DIR . 'libs/Smarty.class.php'); class Product_Smarty extends Smarty { function __construct() { parent::__construct(); $this->setTemplateDir(PRODUCT_DIR . 'templates'); $this->setCompileDir(PRODUCT_DIR . 'templates_c'); $this->setConfigDir(PRODUCT_DIR . 'configs'); $this->setCacheDir(PRODUCT_DIR . 'cache'); } } <file_sep><?php /* Smarty version 3.1.39, created on 2021-08-04 20:38:37 from 'C:\xampp\htdocs\Store\templates\cartitems.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_610adead6926b8_65297870', 'has_nocache_code' => false, 'file_dependency' => array ( '1b3660f537513d0e0302168a4604913725d0019a' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\cartitems.tpl', 1 => 1628102315, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_610adead6926b8_65297870 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_1302034323610adead67e2d5_54045248', 'title'); ?> <link rel="stylesheet" href="css/style.css" type="text/css"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_1238611799610adead67f2b8_24166049', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_1302034323610adead67e2d5_54045248 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_1302034323610adead67e2d5_54045248', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Cart<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_1238611799610adead67f2b8_24166049 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_1238611799610adead67f2b8_24166049', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Items in Cart:</h1> <table border="1" > <thead> <tr> <th scope="col">TYPE</th> <th scope="col">NAME</th> <th scope="col">SIZE</th> <th scope="col">COLOR</th> <th scope="col">PRICE</th> <th scope="col"></th> </tr> </thead> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <tr> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['TYPE'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['NAME'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['SIZE'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['COLOR'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['PRICE'], ENT_QUOTES, 'UTF-8', true);?> </td> <td>BUY</td> </tr> <?php } if ($_smarty_tpl->tpl_vars['entry']->do_else) { ?> <tr> <td>No items</td> </tr> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </table> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-26 20:16:25 from 'C:\xampp\htdocs\Store\templates\landingpage.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60fefbf9dbf5b6_41052629', 'has_nocache_code' => false, 'file_dependency' => array ( 'f6a12120fc3c25cbe51751c5a0fba0213ec1ef09' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\landingpage.tpl', 1 => 1627323385, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60fefbf9dbf5b6_41052629 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_85750955760fefbf9dae843_39386931', 'title'); ?> <link rel="stylesheet" href="css/style.css" type="text/css"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_47948228560fefbf9daff10_29648337', 'body'); $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_85750955760fefbf9dae843_39386931 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_85750955760fefbf9dae843_39386931', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Home<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_47948228560fefbf9daff10_29648337 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_47948228560fefbf9daff10_29648337', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Welcome to our shop , check some of the products available</h1> <div class="row"> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <div class="column" style="border:2px solid black;"> <h3> <?php echo $_smarty_tpl->tpl_vars['entry']->value['DESCRIPTION'];?> </h3> <img src="<?php echo $_smarty_tpl->tpl_vars['entry']->value['IMGPATH'];?> " width="50%" height="50%" object-fit: contain"> <h3> Price:<?php echo $_smarty_tpl->tpl_vars['entry']->value['PRICE'];?> </h3> </div> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-26 20:16:05 from 'C:\xampp\htdocs\Store\templates\contact.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60fefbe51b5548_39160602', 'has_nocache_code' => false, 'file_dependency' => array ( '8d9f3570548adaf44b7a38b01f46d38b38bff63d' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\contact.tpl', 1 => 1627323010, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60fefbe51b5548_39160602 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_136893335860fefbe51b4b14_47676231', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'body'} */ class Block_136893335860fefbe51b4b14_47676231 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_136893335860fefbe51b4b14_47676231', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Contact us</h1> <div class="align-center"> <form action="" method="post"> <h3>Any questions? We would love to hear from you:</h3> <p>Name: <input type="name" id="name"> <p> Email: <input type="email" id="email"> <p> Message: <br> <textarea id="message" name="txt_comments" rows="10" cols="35"> </textarea> <br> <br> <input type="submit" value="NOT WORKING"> </form> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-08-04 20:10:37 from 'C:\xampp\htdocs\Store\templates\index.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_610ad81d643ec0_69377687', 'has_nocache_code' => false, 'file_dependency' => array ( '2afd2f8b62e9fadfd9477009eba90e544dd6c412' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\index.tpl', 1 => 1628100628, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_610ad81d643ec0_69377687 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_662867075610ad81d391819_85226636', 'title'); ?> <link rel="stylesheet" href="css/style.css" type="text/css"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_767033280610ad81d394c33_28664621', 'body'); $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_662867075610ad81d391819_85226636 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_662867075610ad81d391819_85226636', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Home<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_767033280610ad81d394c33_28664621 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_767033280610ad81d394c33_28664621', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Logged In</h1> <?php echo $_SESSION['name'];?> <h1>Items in Cart:</h1> <table border="1"> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <tr> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['NAME'], ENT_QUOTES, 'UTF-8', true);?> </td> </tr> <?php } if ($_smarty_tpl->tpl_vars['entry']->do_else) { ?> <tr> <td>No items</td> </tr> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </table> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-29 18:52:34 from 'C:\xampp\htdocs\Store\templates\Login.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_6102dcd2efaeb1_14442286', 'has_nocache_code' => false, 'file_dependency' => array ( 'cae1cfddbe3f40f166957aa75ce6bd7c67ab95c8' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\Login.tpl', 1 => 1627343058, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_6102dcd2efaeb1_14442286 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_6116942146102dcd2e37d61_82738596', 'body'); $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'body'} */ class Block_6116942146102dcd2e37d61_82738596 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_6116942146102dcd2e37d61_82738596', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <br> <div > <h1>Login</h1> <form action="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=login" method="POST"> <div class="align-center"> <label>Username:</label> <input type="text" name="username"> </div> <br> <div class="align-center"> <label>Password:</label> <input type="<PASSWORD>" name="password" ) > </div> <br> <div class="align-center"> <input type="submit" value="Login"> <p>Don't have an account? <a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=add">Sign up now</a></p> </div> </form> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-20 20:12:47 from 'C:\xampp\htdocs\Store\templates\message.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60f7121f38d696_06551377', 'has_nocache_code' => false, 'file_dependency' => array ( 'b7842944b08a9a1280b185eeb0e30adc2bda4f5e' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\message.tpl', 1 => 1626804752, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60f7121f38d696_06551377 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_37808081360f7121f38a008_76769463', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'body'} */ class Block_37808081360f7121f38a008_76769463 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_37808081360f7121f38a008_76769463', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <br> <?php echo $_smarty_tpl->tpl_vars['text']->value;?> <p><a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=index">Get back</a></p> <?php } } /* {/block 'body'} */ } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of Db * * @author c-a-s */ class Db { public $conn; private function connect() { $this->conn = new PDO("mysql:host=localhost;dbname=simplestore", "root", ""); } private function close() { $this->conn = null; } public function select($query, $params = null) { if (!preg_match("/^SELECT/i", $query)) { throw new Exception('ERROR. NOT SELECT'); } $this->connect(); $result = null; try { if (!empty($params)) { $execute = $this->conn->prepare($query); $execute->execute($params); $result = $execute->fetchAll(); } else { $execute = $this->conn->prepare($query); $execute->execute(); $result = $execute->fetchAll(); } } catch (PDOException $ex) { return false; } $this->close(); return $result; } public function insert($query, $params = null) { if (!preg_match("/^INSERT/i", $query)) { throw new Exception('ERROR. NOT INSERT'); } $this->connect(); try { if (!empty($params)) { $execute = $this->conn->prepare($query); $execute->execute($params); } else { $execute = $this->conn->prepare($query); $execute->execute(); } } catch (PDOException $ex) { return false; } $this->close(); } public function update($query, $params = null) { if (!preg_match("/^UPDATE/i", $query)) { throw new Exception('ERROR. NOT UPDATE'); } $this->connect(); try { if (!empty($params)) { $execute = $this->conn->prepare($query); $execute->execute($params); } else { $execute = $this->conn->prepare($query); $execute->execute(); } } catch (PDOException $ex) { return false; } $this->close(); } public function delete($query, $params = null) { if (!preg_match("/^DELETE/i", $query)) { throw new Exception('ERROR. NOT DELETE'); } $this->connect(); try { if (!empty($params)) { $execute = $this->conn->prepare($query); $execute->execute($params); } else { $execute = $this->conn->prepare($query); $execute->execute(); } } catch (PDOException $ex) { return false; } $this->close(); } } <file_sep>-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Tempo de geração: 12-Jul-2021 às 01:45 -- Versão do servidor: 10.4.19-MariaDB -- versão do PHP: 8.0.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Banco de dados: `simplestore` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `cart` -- CREATE TABLE `cart` ( `CARTID` int(11) NOT NULL, `CLIENT_ID` int(11) NOT NULL, `PRODUCT_ID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Estrutura da tabela `client` -- CREATE TABLE `client` ( `CLIENTID` int(11) NOT NULL, `NAME` varchar(50) NOT NULL, `USERNAME` varchar(50) NOT NULL, `PASSWORD` varchar(50) NOT NULL, `ADDRESS` varchar(50) NOT NULL, `EMAIL` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `client` -- INSERT INTO `client` (`CLIENTID`, `NAME`, `USERNAME`, `PASSWORD`, `ADDRESS`, `EMAIL`) VALUES (51, '<NAME>', 'Cesar', '123456', 'rua rua', '<EMAIL>'); -- -------------------------------------------------------- -- -- Estrutura da tabela `product` -- CREATE TABLE `product` ( `PRODUCTID` int(11) NOT NULL, `TYPE` varchar(50) NOT NULL, `PRICE` float NOT NULL, `DESCRIPTION` varchar(100) DEFAULT NULL, `QUANTITY` int(11) DEFAULT NULL, `SIZE` varchar(5) DEFAULT NULL, `COLOR` varchar(50) DEFAULT NULL, `IMGPATH` varchar(50) DEFAULT NULL, `NAME` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Extraindo dados da tabela `product` -- INSERT INTO `product` (`PRODUCTID`, `TYPE`, `PRICE`, `DESCRIPTION`, `QUANTITY`, `SIZE`, `COLOR`, `IMGPATH`, `NAME`) VALUES (1, 'Pants', 100, 'Normal Pants', 80, 'XS', 'Indigo', 'img\\pants0.png', 'Normal Pants'), (2, 'Pants', 1020, 'Some Pants', 12, 'XS', 'Aquamarine', 'img\\pants1.png', 'Pants 1'), (3, 'Pants', 1020, 'More Pants', 59, '3XL', 'Puce', 'img\\pants2.jpg', 'Pants 2'), (4, 'Pants', 1070, 'More More pants', 69, '2XL', 'Puce', 'img\\pants3.jpg', 'Pants 3'), (5, 'Pants', 1020, 'Pants Pants', 17, '2XL', 'Violet', 'img\\pants5.jpg', 'Pants 5'), (21, 'Shirt', 123, 'Shirt', 23, 'M', 'Blue', 'img\\shirt0.jpg', 'Shirt0'), (22, 'Shirt', 12323, 'Shirt asd ', 23, 'M', 'Blue', 'img\\shirt6.jpg', 'Shirt3'), (23, 'Shirt', 13223, 'Shirt', 233, 'M', 'Blue', 'img\\shirt1.jpg', 'Shirt1'), (24, 'Shirt', 13233, 'Shirt', 23, 'L', 'Green', 'img\\shirt2.jpg', 'Shirt2'), (25, 'Shirt', 13233, 'Shirt', 1, 'M', 'Red', 'img\\shirt3.jpg', 'Shirt3'); -- -- Índices para tabelas despejadas -- -- -- Índices para tabela `cart` -- ALTER TABLE `cart` ADD PRIMARY KEY (`CARTID`), ADD KEY `CLIENT_ID` (`CLIENT_ID`), ADD KEY `PRODUCT_ID` (`PRODUCT_ID`); -- -- Índices para tabela `client` -- ALTER TABLE `client` ADD PRIMARY KEY (`CLIENTID`); -- -- Índices para tabela `product` -- ALTER TABLE `product` ADD PRIMARY KEY (`PRODUCTID`); -- -- AUTO_INCREMENT de tabelas despejadas -- -- -- AUTO_INCREMENT de tabela `cart` -- ALTER TABLE `cart` MODIFY `CARTID` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de tabela `client` -- ALTER TABLE `client` MODIFY `CLIENTID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53; -- -- AUTO_INCREMENT de tabela `product` -- ALTER TABLE `product` MODIFY `PRODUCTID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- Restrições para despejos de tabelas -- -- -- Limitadores para a tabela `cart` -- ALTER TABLE `cart` ADD CONSTRAINT `cart_ibfk_1` FOREIGN KEY (`CLIENT_ID`) REFERENCES `client` (`CLIENTID`), ADD CONSTRAINT `cart_ibfk_2` FOREIGN KEY (`PRODUCT_ID`) REFERENCES `product` (`PRODUCTID`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-02 13:19:52 from 'C:\xampp\htdocs\Store\templates\users.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60def6586bc607_09565189', 'has_nocache_code' => false, 'file_dependency' => array ( '4b7855efcc72baed4910edf21f4e195feb174bad' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\users.tpl', 1 => 1624548203, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60def6586bc607_09565189 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_checkPlugins(array(0=>array('file'=>'C:\\xampp\\htdocs\\Store\\vendor\\smarty\\smarty\\plugins\\function.cycle.php','function'=>'smarty_function_cycle',),)); ?> <table border="0" width="300"> <tr> <th colspan="2" bgcolor="#d1d1d1"> Guestbook Entries (<a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=add">add</a>)</th> </tr> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <tr bgcolor="<?php echo smarty_function_cycle(array('values'=>"#dedede,#eeeeee",'advance'=>false),$_smarty_tpl);?> "> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['USERID'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['NAME'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['USERNAME'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['PASSWORD'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['ADDRESS'], ENT_QUOTES, 'UTF-8', true);?> </td> </tr> <?php } if ($_smarty_tpl->tpl_vars['entry']->do_else) { ?> <tr> <td colspan="2">No records</td> </tr> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </table> <?php } } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-16 19:18:41 from 'C:\xampp\htdocs\Store\templates\newclient.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60f1bf71c95453_26315018', 'has_nocache_code' => false, 'file_dependency' => array ( '56db99d6aa879b055039048ed526bf31b6dcc449' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\newclient.tpl', 1 => 1626455919, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60f1bf71c95453_26315018 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_102800442260f1bf71c15b99_12469458', 'title'); ?> <link rel="stylesheet" href="css/style.css" type="text/css"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_33245122960f1bf71c1d224_18605554', 'body'); $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_102800442260f1bf71c15b99_12469458 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_102800442260f1bf71c15b99_12469458', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> New Client<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_33245122960f1bf71c1d224_18605554 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_33245122960f1bf71c1d224_18605554', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Regist form</h1> <div class="border"> <form action="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=register" method="post"> <h3>Insert your data:</h3> <p>Name:<br> <input type="text" style="width: 30em;" name="name" required> <p>Username:<br> <input type="text" style="width: 30em;" name="username" required> <p>Email:<br> <input type="email" style="width: 30em;" name="email" required> <p>Password:<br> <input type="password" style="width: 30em;" name="password" required> <p>Address:<br> <input type="address" style="width: 30em;" name="address" required> <p><input type="submit" value="Register"> </form> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-04 22:30:26 from 'C:\xampp\htdocs\Store\templates\allclients.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60e21a62758598_71863564', 'has_nocache_code' => false, 'file_dependency' => array ( '12c9bea291397e96b0efff4419933abb55529a2f' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\allclients.tpl', 1 => 1625430613, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60e21a62758598_71863564 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_191601304760e21a624160c1_17985208', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'body'} */ class Block_191601304760e21a624160c1_17985208 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_191601304760e21a624160c1_17985208', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <table border="0"> <tr> <th> All clients(<a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=add">add</a>)</th> </tr> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <tr > <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['CLIENTID'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['NAME'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['USERNAME'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['PASSWORD'], ENT_QUOTES, 'UTF-8', true);?> </td> <td><?php echo htmlspecialchars($_smarty_tpl->tpl_vars['entry']->value['ADDRESS'], ENT_QUOTES, 'UTF-8', true);?> </td> </tr> <?php } if ($_smarty_tpl->tpl_vars['entry']->do_else) { ?> <tr> <td>No records</td> </tr> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </table> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-15 23:37:46 from 'C:\xampp\htdocs\Store\templates\header.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60f0aaaa5cafe1_77642135', 'has_nocache_code' => false, 'file_dependency' => array ( '347338435fee9efa037ba948d977d83fbae1fe6a' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\header.tpl', 1 => 1626385065, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60f0aaaa5cafe1_77642135 (Smarty_Internal_Template $_smarty_tpl) { ?><link rel="stylesheet" href="css/style.css" type="text/css"> <div class="topnav"> <a class="active" href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=index">Home</a> <a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=contact">Contact</a> <a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=about">About</a> <div class="topnav-right"> <a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=registerform">Register</a> <a href="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=loginform">Login</a> </div> </div> <?php } } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require(CLIENT_DIR . 'libs/client.lib'); require_once(SMARTY_DIR . 'libs/Smarty.class.php'); class Client_Smarty extends Smarty { function __construct() { parent::__construct(); $this->setTemplateDir(CLIENT_DIR . 'templates'); $this->setCompileDir(CLIENT_DIR . 'templates_c'); $this->setConfigDir(CLIENT_DIR . 'configs'); $this->setCacheDir(CLIENT_DIR . 'cache'); } } <file_sep># Store Web-Commerce project learning Php and Smarty <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-26 20:20:13 from 'C:\xampp\htdocs\Store\templates\layout.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60fefcdd67a758_28993872', 'has_nocache_code' => false, 'file_dependency' => array ( '9436f5ddd29034375ef35d9c1afd2acec756d155' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\layout.tpl', 1 => 1627323613, 2 => 'file', ), ), 'includes' => array ( 'file:headerLogged.tpl' => 1, 'file:header.tpl' => 1, 'file:footer.tpl' => 1, ), ),false)) { function content_60fefcdd67a758_28993872 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, false); ?> <html> <head> <title><?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_105056974560fefcdd65e5c3_57410163', 'title'); ?> </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <header> <?php if ($_SESSION != null) {?> <?php $_smarty_tpl->_subTemplateRender('file:headerLogged.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false); ?> <?php } else { ?> <?php $_smarty_tpl->_subTemplateRender('file:header.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false); ?> <?php }?> </header> <body class="content"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_159811826060fefcdd678b98_26786443', 'body'); ?> </body> <footer> <?php $_smarty_tpl->_subTemplateRender('file:footer.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, $_smarty_tpl->cache_lifetime, array(), 0, false); ?> </footer> </html> <?php } /* {block 'title'} */ class Block_105056974560fefcdd65e5c3_57410163 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_105056974560fefcdd65e5c3_57410163', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Default Page Title<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_159811826060fefcdd678b98_26786443 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_159811826060fefcdd678b98_26786443', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-29 18:52:45 from 'C:\xampp\htdocs\Store\templates\buying.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_6102dcdd44fdf9_06299842', 'has_nocache_code' => false, 'file_dependency' => array ( '378211c8e9324b0b443d1587c789f9a30bdc6d2f' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\buying.tpl', 1 => 1627494727, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_6102dcdd44fdf9_06299842 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_21100175136102dcdd448cd2_22140928', 'title'); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_7933911466102dcdd449c85_19991502', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_21100175136102dcdd448cd2_22140928 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_21100175136102dcdd448cd2_22140928', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Buying<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_7933911466102dcdd449c85_19991502 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_7933911466102dcdd449c85_19991502', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h5>Product: <?php echo $_smarty_tpl->tpl_vars['data']->value['productname'];?> </h5> <div class="row"> <div class="column" > <img src="<?php echo $_smarty_tpl->tpl_vars['data']->value['img'];?> " width="50%" height="50%" object-fit: contain"> </div> <div class="column" > <p>Billing information:</p> <form> Name:<textarea type="text" name="name" rows="4" cols="50"><?php echo $_smarty_tpl->tpl_vars['data']->value['name'];?> </textarea> <p> Address: <textarea type="text" name="address" rows="4" cols="50"> <?php echo $_smarty_tpl->tpl_vars['data']->value['address'];?> </textarea> <p> <input type="submit" value="Buy" /> </form> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-27 19:12:28 from 'C:\xampp\htdocs\Store\templates\productlist.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_61003e7c039389_03937083', 'has_nocache_code' => false, 'file_dependency' => array ( 'de7f89b0c99bc5dd2d0d2c10d29c5c5707fe50d3' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\productlist.tpl', 1 => 1627405946, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_61003e7c039389_03937083 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_130430715661003e7c02e8d2_16978261', 'title'); ?> <link rel="stylesheet" href="css/style.css" type="text/css"> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_139128721361003e7c02f2b2_76393065', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'title'} */ class Block_130430715661003e7c02e8d2_16978261 extends Smarty_Internal_Block { public $subBlocks = array ( 'title' => array ( 0 => 'Block_130430715661003e7c02e8d2_16978261', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> Product List<?php } } /* {/block 'title'} */ /* {block 'body'} */ class Block_139128721361003e7c02f2b2_76393065 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_139128721361003e7c02f2b2_76393065', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>Products</h1> <div class="row"> <?php $_from = $_smarty_tpl->smarty->ext->_foreach->init($_smarty_tpl, $_smarty_tpl->tpl_vars['data']->value, 'entry'); $_smarty_tpl->tpl_vars['entry']->do_else = true; if ($_from !== null) foreach ($_from as $_smarty_tpl->tpl_vars['entry']->value) { $_smarty_tpl->tpl_vars['entry']->do_else = false; ?> <div class="column" style="border:2px solid black;"> <form action="<?php echo $_smarty_tpl->tpl_vars['SCRIPT_NAME']->value;?> ?action=productdestination" method="POST"> <input type="hidden" name="id" value="<?php echo $_smarty_tpl->tpl_vars['entry']->value['PRODUCTID'];?> "/> <h3><?php echo $_smarty_tpl->tpl_vars['entry']->value['DESCRIPTION'];?> </h3> <img src="<?php echo $_smarty_tpl->tpl_vars['entry']->value['IMGPATH'];?> " width="50%" height="50%" object-fit: contain"> <h3>Price:<?php echo $_smarty_tpl->tpl_vars['entry']->value['PRICE'];?> </h3> <div> <input type="submit" name="destination" value="Add to cart"/> <input type="submit" name="destination" value="Buy" style="float:right;"/> </div> </form> </div> <?php } $_smarty_tpl->smarty->ext->_foreach->restore($_smarty_tpl, 1);?> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* Smarty version 3.1.39, created on 2021-07-26 19:49:31 from 'C:\xampp\htdocs\Store\templates\about.tpl' */ /* @var Smarty_Internal_Template $_smarty_tpl */ if ($_smarty_tpl->_decodeProperties($_smarty_tpl, array ( 'version' => '3.1.39', 'unifunc' => 'content_60fef5ab767a19_48759819', 'has_nocache_code' => false, 'file_dependency' => array ( 'cc69bc4d359a9d823302a149b47bab47632af296' => array ( 0 => 'C:\\xampp\\htdocs\\Store\\templates\\about.tpl', 1 => 1627321733, 2 => 'file', ), ), 'includes' => array ( ), ),false)) { function content_60fef5ab767a19_48759819 (Smarty_Internal_Template $_smarty_tpl) { $_smarty_tpl->_loadInheritance(); $_smarty_tpl->inheritance->init($_smarty_tpl, true); ?> <?php $_smarty_tpl->inheritance->instanceBlock($_smarty_tpl, 'Block_206160492860fef5ab764f54_89608153', 'body'); ?> <?php $_smarty_tpl->inheritance->endChild($_smarty_tpl, "layout.tpl"); } /* {block 'body'} */ class Block_206160492860fef5ab764f54_89608153 extends Smarty_Internal_Block { public $subBlocks = array ( 'body' => array ( 0 => 'Block_206160492860fef5ab764f54_89608153', ), ); public function callBlock(Smarty_Internal_Template $_smarty_tpl) { ?> <h1>About us</h1> <div class="row"> <div class="column" > </div> <div class="column" > <img src="<?php echo $_smarty_tpl->tpl_vars['img']->value;?> " width="50%" height="50%" object-fit: contain"> </div> <div class="column" > <h2>company name</h2> <p>email:</p> <p></p> </div> <div class="column" > </div> </div> <?php } } /* {/block 'body'} */ } <file_sep><?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of mail * * @author c-a-s */ use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; class mail { public function Send($email, $subject, $body) { $mail = new PHPMailer(true); try { //Server settings //$mail->SMTPDebug = SMTP::DEBUG_SERVER; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = '<EMAIL>'; $mail->Password = '<PASSWORD>'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; //Recipients $mail->setFrom('<EMAIL>', 'SimpleStore'); $mail->addAddress($email); //Content $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $body; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } } <file_sep><?php session_start(); //directories define('CLIENT_DIR', '../Store/'); define('CART_DIR', '../Store/'); define('PRODUCT_DIR', '../Store/'); define('SMARTY_DIR', 'C:/xampp/htdocs/Store/vendor/smarty/smarty/'); // setups include(CLIENT_DIR . 'libs/client_setup.php'); include(CART_DIR . 'libs/cart_setup.php'); include(PRODUCT_DIR . 'libs/product_setup.php'); //class instance $client = new Client(); $cart = new Cart(); $product = new Product(); // set the current action $_action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'index'; echo $_action; switch ($_action) { case 'loginform': $client->showloginform(); break; case 'login': $client->login(); break; case 'logout': $client->logout(); break; case 'contact': $cart->showcontact(); break; case 'about': $cart->showabout(); break; case 'products': $product->listproducts(); break; case 'registerform': $client->displayregform(); break; case 'register': $client->newclient($_POST); break; case 'verification': $client->accountvalidation(); break; case 'productdestination': $product->productdestination(); break; case 'index': $cart->index(); break; case 'clients': $client->displayclients($client->getall()); break; case 'cart': $cart->showcart(); break; default: break; } ?>
2396ae41f5d8b5afdde3b8c36b41d31d939dba8a
[ "Markdown", "SQL", "PHP" ]
21
PHP
cesarf99/Store
d7d328c0b5e624e3e52eb15426cd648f6e5b9fe8
b96efc7c1cabd659ac15ea3b4c804f00fcd16238
refs/heads/master
<repo_name>kwangmin-park/React_docs_prac<file_sep>/ch8.js // ch8. 리스트와 key // js에서의 map const numbers = [1,2,3,4,5]; const doubled = numbers.map((number) => number * 2); //[2,4,6,8,10] console.log(doubled); // react에서의 map 사용 예시 const listItems = numbers.map((number) => <li>{number}</li>); ReactDOM.render( <ul>{listItems}</ul>, document.getElementById('root') ); // 컴포넌트 안에서 리스트 렌더링 function NumberList(props){ const numbers = pops.numbers; // element list를 만들때 각 항목에 key를 할당해야한다. // key는 React가 어떤 항목을 변경, 추가, 삭제할지 식별하는 것을 돕는다.(고유성) // 엘리먼트 리스트에 key를 명시하지 않으면 기본적으로 인덱스를 key로 설정하나 이는 권장되지 않는다. // key는 하위 컴포넌트의 props로 넘어가지 않는다.(리액트에 도움을 주는 역할) const listItems = numbers.map((number) => <li key={number.toString()}>{number}</li>); return ( <ul>{listItems}</ul> ); } ReactDOM.render( <NumberList numbers ={numbers} />, document.getElementById('root') ); <file_sep>/ch6.js // React 연습 ch6. 이벤트 처리하기 // HTML 버전 <button onclick="activeLaser()"> Activate Lasers </button> // react 버전 <button onClick={activateLasers}> Activate Lasers </button> // React에서는 false를 반환해도 기본 동작을 방지할 수 없다. 반드시 preventDefault를 명시적으로 호출해야한다. function Form(){ function handleSubmit(e){ e.preventDefault(); console.log("you clicked submit."); } return( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); } // React를 사용할 때 DOM 엘리먼트가 생성된 후 리스너를 추가하기 위해 addEventListener를 호출할 필요 없이 엘리먼트가 처음 렌더링 될 때 리스너를 제공하면 된다. // 일반적으로 이벤트 핸들러를 클래스의 메서드로 만드는 것. class Toggle extends React.Component{ constructor(props){ super(props); this.state = {isToggleOn : true}; // 콜백에서 this가 작동하려면 아래와 같이 바인딩해줘야 한다. this.handleClick = this.handleClick.bind(this); } // JS에서 클래스 메서드는 기본적으로 바인딩 되어 있지 않으므로 this.handleClick을 바인딩하지 않고 onClick에 전달할 경우 실제 this는 undefined가 된다. ()를 사용하지 않고 메서드를 참조할 경우는 해당 메서드를 바인딩해야한다. handleClick(){ this.setState(prevState => ({ isToggleOn : !prevState.isToggleOn })); } render(){ return ( <button onClick={this.handleClick}> //함수와 다르게 this를 안붙이면 인식하지 못함. 주의. {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } }
c3111474fb252a224d64614c1858089b4c656259
[ "JavaScript" ]
2
JavaScript
kwangmin-park/React_docs_prac
2e33af622e100a0c9c09db13617a08bddf14c195
8a0fc749e8d4182382e4f271aca9daf1a58a123c
refs/heads/master
<file_sep>import {Injector} from '@angular/core'; export function InjectorUtils(provider: any): any { const injector = Injector.create({providers: [{provide: provider, deps: []}]}); return injector.get(provider); } <file_sep>import {TranslateService} from '@ngx-translate/core'; // @dynamic export abstract class TranslateUtils { private static translateService: TranslateService; static setTranlateInstance (translateService: TranslateService) { if (!this.translateService && translateService) { this.translateService = translateService; } } static Translate(text: string): string { if (this.translateService) { let translation = ''; this.translateService.get(text).subscribe( trans => { translation = trans; }); return translation; } else { return text; } } } <file_sep>import {animate, state, style, transition, trigger, keyframes, query, stagger, AnimationTriggerMetadata} from '@angular/animations'; export function routerTransition(): AnimationTriggerMetadata { return slideToLeft(); // slideToTop } export function LoginRouterTransition(): AnimationTriggerMetadata { return slideToTop(); // slideToTop } export function sidebarAnim(name): void { trigger('slideInOut', [ state('in', style({ transform: 'translate3d(20%, 0, 0)' })), state('out', style({ transform: 'translate3d(100%, 0, 0)' })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]); } export function slideToRight(): AnimationTriggerMetadata { return trigger('routerTransition', [ state('void', style({})), state('*', style({})), transition(':enter', [ style({ transform: 'translateX(-100%)' }), animate('0.5s ease-in-out', style({ transform: 'translateX(0%)' })) ]), transition(':leave', [ style({ transform: 'translateX(0%)' }), animate('0.5s ease-in-out', style({ transform: 'translateX(100%)' })) ]) ]); } export function slideToLeft(): AnimationTriggerMetadata { return trigger('routerTransition', [ state('void', style({})), state('*', style({})), transition(':enter', [ style({ transform: 'translateX(100%)' }), animate('0.5s ease-in-out', style({ transform: 'translateX(0%)' })) ]), transition(':leave', [ style({ transform: 'translateX(0%)' }), animate('0.5s ease-in-out', style({ transform: 'translateX(-100%)' })) ]) ]); } export function slideToBottom(): AnimationTriggerMetadata { return trigger('routerTransition', [ state('void', style({})), state('*', style({})), transition(':enter', [ style({ transform: 'translateY(-100%)' }), animate('0.5s ease-in-out', style({ transform: 'translateY(0%)' })) ]), transition(':leave', [ style({ transform: 'translateY(0%)' }), animate('0.5s ease-in-out', style({ transform: 'translateY(100%)' })) ]) ]); } export function slideToTop(): AnimationTriggerMetadata { return trigger('routerTransition', [ state('void', style({})), state('*', style({})), transition(':enter', [ style({ transform: 'translateY(100%)' }), animate('0.5s ease-in-out', style({ transform: 'translateY(0%)' })) ]), transition(':leave', [ style({ transform: 'translateY(0%)' }), animate('0.5s ease-in-out', style({ transform: 'translateY(-100%)' })) ]) ]); } export function slideInOutAnimationSideBar (): AnimationTriggerMetadata { return trigger('slideInOutAnimationSideBar', [ // end state styles for route container (host) state('in', style({ // the view covers the whole screen with a semi tranparent background left: 60, width: 60, marginLeft: -60, })), state('out', style({ // the view covers the whole screen with a semi tranparent background left: 235, width: 235, marginLeft: -235, })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]); } export const slideInOutAnimationContent = trigger('slideInOutAnimationContent', [ // end state styles for route container (host) state('in', style({ // the view covers the whole screen with a semi tranparent background left: 60, width: 60, marginLeft: -60, })), state('out', style({ // the view covers the whole screen with a semi tranparent background left: 235, width: 235, marginLeft: -235, })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]); export function fideInFadeOut(): AnimationTriggerMetadata { return trigger('simpleFadeAnimation', [ // the "in" style determines the "resting" state of the element when it is visible. state('in', style({opacity: 1})), // fade in when created. this could also be written as transition('void => *') transition(':enter', [ style({opacity: 0}), animate(600 ) ]), // fade out when destroyed. this could also be written as transition('void => *') transition(':leave', animate(600, style({opacity: 0}))) ]); } <file_sep>export interface WidthHeightMed { width?: number; height?: number; Media?: number; fullScreen?: boolean; } <file_sep>import {SessionUtils} from './sessionUtils'; import {GlobalUtils} from './globalUtils'; // @dynamic export abstract class BreadCrumbUtils { static getBreadCrumb (): string { return SessionUtils.getSession('breadcrumb'); } static setBreadCrumb(value: string, isDinamic?: boolean): void { if (!isDinamic) { value = GlobalUtils.getSysname() + value; } SessionUtils.setSession('breadcrumb', value); } static getPrinModFromBreadCrumb (value: string): string { const search = value.split(/\//); return search[1]; } } <file_sep>// @dynamic export abstract class ObjectUtils { static isObject(obj: any): boolean { return (typeof obj === 'object'); } static isEmpty (obj: any): boolean { return (this.isObject(obj) && (JSON.stringify(obj) === JSON.stringify({}))); } static isEmptyCircular (obj: any): boolean { let isEmpty = true; Object.keys(obj).forEach(key => { isEmpty = false; }); return isEmpty; } static copyNestedObject (myObject: object): any { return {...myObject}; // JSON.parse(JSON.stringify(myObject)); } static copyObject (myObject: object): {} & object { return this.copyNestedObject(myObject); } static objectToNum (obj: any): any { const newObj: any = {}; Object.keys(obj).forEach(prop => { newObj[prop] = +obj[prop]; }); } static merge(obj1 = {}, obj2 = {}): object { return {...obj1, ...obj2}; } } <file_sep>import {SessionUtils} from './sessionUtils'; import {TranslateUtils} from './translateUtils'; import notify from 'devextreme/ui/notify'; import {EncryptUtils} from './encryptUtils'; import {ObjectUtils} from './objectUtils'; import {GlobalUtils} from './globalUtils'; // @dynamic export abstract class LoginUtils { private static LoginKey() { if (EncryptUtils.hasEncryption()) { return btoa(EncryptUtils.encrypt(this.getCurrentUser())); } else { return btoa(JSON.stringify(this.getCurrentUser())); } } static isLoggedin(): boolean { let key: string; if (EncryptUtils.hasEncryption()) { key = EncryptUtils.decrypt(atob(SessionUtils.getSession('isLoggedin'))); return GlobalUtils.areEquals(key, this.getCurrentUser()); } else { const log = SessionUtils.getSession('isLoggedin'); if (log === null) { return false; } key = atob(log); return GlobalUtils.areEquals(JSON.parse(key), this.getCurrentUser()); } } static setLoggedin(): void { SessionUtils.setSession('isLoggedin', this.LoginKey()); } static logOff(): void { sessionStorage.clear(); } static logFail (err) { this.logOff(); const men = TranslateUtils.Translate(err.statusText); notify(men, 'error', 5000); } static setCurrentUser(value: any): void { SessionUtils.setSession('currentUser', value); } static getCurrentUser(): any { return SessionUtils.getSession('currentUser'); } static setEmpresasUser (empresas: any[]): void { SessionUtils.setSession('empresasUser', empresas); } static getEmpresasUser (): any[] { return SessionUtils.getSession('empresasUser'); } static getEmresaIdProd (): any { const {IDEmpresaProd} = this.getCurrentUser(); return IDEmpresaProd; } static setEmpresaCode (id: number, nombre?: string): void { const crr = this.getCurrentUser(); crr.CompanyCode = id; if (nombre) { crr.CompanyName = nombre; } this.setCurrentUser(crr); } static getEmpresaCode (): any { const {CompanyCode} = this.getCurrentUser(); return CompanyCode; } } <file_sep>// @dynamic export abstract class FechasUtils { static toDate (DateOri, RemoveHour?): any { let DateObj = DateOri; if (DateOri) { try { const isDate = (typeof DateObj.getMonth === 'function'); if (!isDate) { const part = DateObj.split('.'); DateObj = Date.parse(part[0]); } if (RemoveHour) { DateObj.setHours(0, 0, 0, 0); } return DateObj; } catch (e) { } } return null; } static unsetTimeZero(time: string): string { return time ? time.replace( /0001-01-01T00:00:00\.0000000/, '') : ''; } static unsetAnytimeZero (set: any): any { Object.keys(set).forEach(prop => { if (set[prop] === '0001-01-01T00:00:00.0000000') { set[prop] = this.unsetTimeZero(set[prop]); } }); return set; } static unsetArrayTimeZero (set: any[]): any[] { const final: any[] = []; for (let s of set) { s = this.unsetAnytimeZero(s); final.push(s); } return final; } static isWeekend(date): boolean { const day = date.getDay(); return day === 0 || day === 6; } static isToday(date): boolean { const today = new Date; return (date === today); } } <file_sep>// @dynamic export abstract class DomElementUtils { static getContainerElement(element: string) { return new Promise(function (resolve, reject) { DomElementUtils.waitForContainerElement(element, resolve); }); } static getContainerClassElement(className: string) { return new Promise(function (resolve, reject) { DomElementUtils.waitForContainerClassElement(className, resolve); }); } private static waitForContainerElement(id, resolve) { const $configElement = document.getElementById(id); if (!$configElement || $configElement === null) { setTimeout(DomElementUtils.waitForContainerElement.bind(this, id, resolve), 30); } else { resolve($configElement); } } private static waitForContainerClassElement(className, resolve) { const $configElement = document.getElementsByClassName(className); if (!$configElement || $configElement === null) { setTimeout(DomElementUtils.waitForContainerClassElement.bind(this, className, resolve), 30); } else { resolve($configElement); } } } <file_sep>import {Router} from '@angular/router'; import {DomSanitizer} from '@angular/platform-browser'; import {TranslateService} from '@ngx-translate/core'; export interface IceUtilitiesData { responsiveWidth?: number; timeshow?: number; router: Router; dynamicDir?: string; staticDir?: string; notAllowed?: string; listDir?: string; sanitizer?: DomSanitizer; translateService?: TranslateService; encryptionKey?: string; } <file_sep>import {Base64} from './base64'; import {DomSanitizer, SafeUrl} from '@angular/platform-browser'; import {md5} from './md5'; // @dynamic export abstract class StringUtils { private static sanitizer: DomSanitizer; static setSanitizerInstance (sanitizer: DomSanitizer) { if (!this.sanitizer && sanitizer) { this.sanitizer = sanitizer; } } static includes(str: string, find: string): boolean { return str.includes(find); } static startsWith(str: string, find: string): boolean { return str.startsWith(find); } static endsWith(str: string, find: string): boolean { return str.endsWith(find); } static isString(val: any): boolean { return (typeof val === 'string' || val instanceof String); } static removeAccents (text: string): string { return text ? text.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : ''; } static StringToNumber (st: string): number { return parseInt(st, 10); } static Utf8Encode (st: string): string { // return this.b64._utf8_encode(st); // const sst = this.utf8.utf8decode(st); return st; } static Utf8Decode (st: string): string { // return this.b64._utf8_decode(st); // const sst = this.utf8.utf8decode(st); return st; } static base64Decode (bb: string): string { const b64 = new Base64(); return b64.decode(bb); } static isEmpty(text: string): boolean { return (text === ''); } static bypassSecurityTrustUrl(text: string): SafeUrl { return this.sanitizer.bypassSecurityTrustUrl(text); } static toMd5(text: string): string { return md5(text); } } <file_sep>import {ArrayUtils} from './utilities/arrayUtils'; import {FechasUtils} from './utilities/fechasUtils'; import {GlobalUtils} from './utilities/globalUtils'; import {LocalStorageUtils} from './utilities/localStorageUtils'; import {LoginUtils} from './utilities/loginUtils'; import {ObjectUtils} from './utilities/objectUtils'; import {RouterUtils} from './utilities/routerUtils'; import {SessionUtils} from './utilities/sessionUtils'; import {StringUtils} from './utilities/stringUtils'; import {TranslateUtils} from './utilities/translateUtils'; import {IceUtilitiesData} from './interfaces/IceUtilitiesData'; import {BreadCrumbUtils} from './utilities/breadCrumbUtils'; import {DomElementUtils} from './utilities/domElementUtils'; import {EncryptUtils} from './utilities/encryptUtils'; export abstract class IceUtilities { static arrays = ArrayUtils; static breadCrumbs = BreadCrumbUtils; static domElements = DomElementUtils; static dates = FechasUtils; static globals = GlobalUtils; static localStorage = LocalStorageUtils; static login = LoginUtils; static objects = ObjectUtils; static router = RouterUtils; static session = SessionUtils; static strings = StringUtils; static translate = TranslateUtils; static encryption = EncryptUtils; static iniIceUtilities(data: IceUtilitiesData) { this.globals.setResponsiveWidth(data.responsiveWidth); this.globals.setTimeShow(data.timeshow); this.router.setRouterInstance(data.router); this.router.setDynamicDir(data.dynamicDir); this.router.setStaticDir(data.staticDir); this.router.setNotAllowedDir(data.notAllowed); this.router.setListDir(data.listDir); this.strings.setSanitizerInstance(data.sanitizer); this.translate.setTranlateInstance(data.translateService); this.encryption.setKey(data.encryptionKey); } } <file_sep>import {PRIMARY_OUTLET, Router, UrlSegment, UrlSegmentGroup, UrlTree} from '@angular/router'; import {TranslateUtils} from './translateUtils'; import {SessionUtils} from './sessionUtils'; import {ArrayUtils} from './arrayUtils'; import {StringUtils} from './stringUtils'; // @dynamic export abstract class RouterUtils { private static router: Router; private static dynamicDir = ''; private static staticDir = ''; private static dynamicDirR = ''; private static staticDirR = ''; private static notAllowed = '/'; private static listDir = 'list'; static setRouterInstance (router?: Router) { if (!this.router && router) { this.router = router; } } static setStaticDir (dir: string) { if (!this.staticDir && dir) { this.staticDir = `/${dir}/`; this.staticDirR = `/${dir}R/`; } } static setDynamicDir (dir: string) { if (!this.dynamicDir && dir) { this.dynamicDir = `/${dir}/`; this.dynamicDirR = `/${dir}R/`; } } static setNotAllowedDir (dir: string) { if (!this.notAllowed && dir) { this.notAllowed = dir; } } static setListDir (dir: string) { if (!this.listDir && dir) { this.listDir = dir; } } static getRerouteUrl (modulo: string, tipo: string, end?: any): string { if (this.router) { let url: string; const mod = modulo.toUpperCase(); const tt = tipo.toUpperCase(); const urlroute: string = this.router.url; if (StringUtils.includes(urlroute, `/${mod}/`)) { url = `/${mod}R/${tt}/`; } else if (StringUtils.includes(urlroute, `/${mod}R/`)) { url = `/${mod}/${tt}/`; } if (end) { url += end.toString(); } return url; } else { return '/'; } } static setDinamicDirUrl(mod: string, id: number): string { return `${this.dynamicDir}${mod.toUpperCase()}/${id.toString()}`; } static setCustomDirUrl(sys: string, mod: string): string { return `${this.staticDir}${sys}/${mod}`; } static evalPerm (extra?: any): void { if (this.router) { let url: string = this.router.url; const sinDrouter = url.split('('); url = sinDrouter[0]; if (StringUtils.includes(url, ';')) { const surl = url.split(';'); url = surl[0]; } if (extra) { url = url.replace(extra, ''); } if (StringUtils.includes(url, this.dynamicDirR)) { url = url.replace(this.dynamicDirR, this.dynamicDir); } else if (StringUtils.includes(url, this.staticDirR)) { url = url.replace(this.staticDirR, this.staticDir); } if ( ( StringUtils.includes(url, this.dynamicDir) || StringUtils.includes(url, this.staticDirR) || StringUtils.includes(url, this.staticDir) || StringUtils.includes(url, this.staticDirR) ) && this.urlNotAllowed(url) ) { this.router.navigate([this.notAllowed]); } } else { this.router.navigate([this.notAllowed]); } } static getSegmentsRoute(route: string, params: any = {}, lista = false): (any | any)[] { const tree: UrlTree = this.router.parseUrl(route); const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; const final: any[] = s.map(p => { return p.path; }); if (lista) { return [...final, ...[this.listDir], ...[params]]; } else { return [...final, ...[params]]; } } static getSegmentsRouteId(route: string, id: number, params: any = {}, lista = false): (any | any)[] { const tree: UrlTree = this.router.parseUrl(route); const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; const final: any[] = s.map(p => { return p.path; }); if (lista) { return [...final, ...[id.toString()], ...['Lista'], ...[params]]; } else { return [...final, ...[id.toString()], ...[params]]; } } static setNotAllowMen (men: string): void { SessionUtils.setSession('notallowedmen', men); } static getNotAllowMen (menset: string): string { let men: any = SessionUtils.getSession('notallowedmen'); if (men !== null) { SessionUtils.deleteSession('notallowedmen'); } else { men = menset; } return TranslateUtils.Translate(men); } static setAllowedUrl (url: any): void { SessionUtils.setSession('allowedurl', url); } static urlNotAllowed (url: string): boolean { const urlsAllowed = SessionUtils.getSession('allowedurl'); let notA = true; if (urlsAllowed !== null) { notA = ArrayUtils.notInArray(urlsAllowed, url); } return notA; } } <file_sep>import {SessionUtils} from './sessionUtils'; import {StringUtils} from './stringUtils'; import {ObjectUtils} from './objectUtils'; import {TranslateUtils} from './translateUtils'; import notify from 'devextreme/ui/notify'; import {WidthHeightMed} from '../interfaces/WidthHeightMed'; // @dynamic export abstract class GlobalUtils { private static responsiveWidth = 960; private static timeshow = 8000; static setResponsiveWidth(responsiveWidth: number): void { if (!this.responsiveWidth && responsiveWidth) { this.responsiveWidth = responsiveWidth; } } static setTimeShow(timeshow: number) { if (!this.timeshow && timeshow) { this.timeshow = timeshow; } } static areEquals(obj1: any, obj2: any): boolean { return JSON.stringify(obj1) === JSON.stringify(obj2); } static isEmptyData(data: any): boolean { return (this.areEquals(data, '') || this.areEquals(data, 0) || data === null || this.areEquals(data, {}) || this.areEquals(data, [])); } static isUndefined(data: any): boolean { return typeof data === 'undefined'; } static setSysname (name: string): void { SessionUtils.setSession('sysname', name); } static getSysname (): string { return SessionUtils.getSession('sysname'); } static autoFixSidebarState (width: number, actstt: string): string { if (width <= this.responsiveWidth) { return 'inres'; } else { if (actstt === 'inres') { return 'out'; } else { return actstt; } } } static fixsidebarState (stt: string, width: number, actstt: string, responsiveWidth: number): string { if (width <= responsiveWidth) { if (actstt === 'inres') { return 'in'; } else { return 'inres'; } } else { return stt; } } static fixContainerState (stt: string, width: number, responsiveWidth: number): string { if (width <= responsiveWidth) { return 'inres'; } else { return stt; } } static successNotify(men: string, data: any) { notify(TranslateUtils.Translate(men) + ' ' + JSON.stringify(data), 'success', this.timeshow); } static cathNotify (error, men: string, type = 'warning'): void { const tmen = TranslateUtils.Translate(men); this.notifyError(tmen, error, type); } private static notifyError (tmen: string, error: string, type: string) { notify(`${tmen} :${this.errorCath(error)}`, type, this.timeshow); if (type === 'error') { throw new Error(tmen); } } static cathNotifyExtraMen (error, men: string, extraMen: string, type = 'warning'): void { const tmen = `${TranslateUtils.Translate(men)} ${extraMen}`; this.notifyError(tmen, error, type); } static errorCath (error: any): string { let errorMen = ''; if (StringUtils.isString(error)) { errorMen = error; } else if (ObjectUtils.isObject(error)) { if (error.error) { if (StringUtils.isString(error.error)) { errorMen = error.error; } else if (ObjectUtils.isObject(error.error) && error.error.ResponseStatus) { if (error.error.ResponseStatus.Message) { errorMen = error.error.ResponseStatus.Message; } else if (error.error.ResponseStatus.ErrorCode) { errorMen = error.error.ResponseStatus.ErrorCode; } } else if (StringUtils.isString(error.message)) { errorMen = error.message; } } else { if (error.message) { errorMen = error.message; } else if (error.statusText) { errorMen = error.statusText; } } } return TranslateUtils.Translate(errorMen); } static getNativeWindow (): Window { return window; } static openWindow(url: string, config?: any): Window | null { return window.open(url, '', 'location=no,width=1800,height=900,scrollbars=yes,top=100,left=700,resizable = no'); } static setWithHeight (whm?: WidthHeightMed): any { if (whm && whm.fullScreen) { return { fullscreen: 1, }; } let mm = 1.5; if (whm && whm.Media) { mm = whm.Media; } const val = { width: window.innerWidth / mm, height: window.innerHeight / mm }; if (whm && whm.hasOwnProperty('width')) { val.width = whm.width; } if (whm && whm.hasOwnProperty('height')) { val.height = whm.height; } return val; } } <file_sep>import {EncryptUtils} from './encryptUtils'; import {ObjectUtils} from './objectUtils'; // @dynamic export abstract class LocalStorageUtils { private static codeKey(key: string) { return btoa(key.toUpperCase()); } static setStorage(key: string, value: any): void { if (EncryptUtils.hasEncryption()) { localStorage.setItem(this.codeKey(key), EncryptUtils.encrypt(value)); } else { let val: any; if (ObjectUtils.isObject(value)) { val = JSON.stringify(value); } else { val = value; } localStorage.setItem(key, val); } } static deleteStorage(key: string): void { if (EncryptUtils.hasEncryption()) { localStorage.removeItem(this.codeKey(key)); } else { localStorage.removeItem(key); } } static getstorage(key: string): any { if (EncryptUtils.hasEncryption()) { return EncryptUtils.decrypt(localStorage.getItem(this.codeKey(key))); } else { let val = localStorage.getItem(key); try { val = JSON.parse(val); } catch (e) {} return val; } } } <file_sep>import {GlobalUtils} from './globalUtils'; // @dynamic export abstract class ArrayUtils { static inArray(array: any[], find: any): boolean { return array.includes(find); } static notInArray(array: any[], find: any): boolean { return (!this.inArray(array, find)); } static objectInArray (arr: any[], obj: any): boolean { return (arr.find(oo => GlobalUtils.areEquals(oo, obj))); } static objectNotInArray (arr: any[], obj: any): boolean { return !this.objectInArray(arr, obj); } static objectPropInArray (arr: any[], prop: string, value: any): boolean { return (arr.find(oo => GlobalUtils.areEquals(oo[prop], value))); } static objectNotPropInArray (arr: any[], prop: string, value: any): boolean { return (!this.objectPropInArray(arr, prop, value)); } static cloneArray (arr: any[]): any[] { return [...arr]; } static removeFromArray (arr: any[], ind: number): any[] { arr.splice(ind, 1); return arr; } static arrayMerge (arr1: any[], arr2: any[]): any[] { return [...arr1, ...arr2]; } } <file_sep>/* * Public API Surface of ice-utilities */ export * from './lib/ice-utilities'; export * from './lib/utilities/injectorUtils'; export * from './lib/utilities/router.animations'; export * from './lib/interfaces/IceUtilitiesData';
bdacaf7d8fa978d52dc0d9267e7ea6d4e5331f18
[ "TypeScript" ]
17
TypeScript
icemanven/ice-libraries
75e225462fdf7c3c70d8f6658d43c8bdbdb3efad
d700398ff0e58154574b8e43e14d947bea6cfe52
refs/heads/main
<repo_name>ECJ222/nuxt-page-visibility<file_sep>/lib/visibility.js // eslint-disable-next-line let state = { isVisible: true, isSupported: true } let hidden = 'hidden' let visibilityChange = 'visibilityChange' if (typeof document !== 'undefined') { if (typeof document.hidden !== 'undefined') { hidden = 'hidden' visibilityChange = 'visibilitychange' } else if (typeof document.msHidden !== 'undefined') { hidden = 'msHidden' visibilityChange = 'msvisibilitychange' } else if (typeof document.webkitHidden !== 'undefined') { hidden = 'webkitHidden' visibilityChange = 'webkitvisibilitychange' } else { state.isSupported = false // eslint-disable-next-line console.warn('This browser does not support page visibility api.') } const handleVisibilityChange = () => { if (document[hidden]) { state.isVisible = false } else { state.isVisible = true } } document.addEventListener(visibilityChange, handleVisibilityChange) } export default () => state <file_sep>/test/module.test.js // module tests import Visibility from '../lib/visibility' describe('Module test', () => { const { isSupported } = Visibility() test('Should be equal to true', () => { expect(isSupported).toBe(true) }) }) <file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [0.0.24](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.23...v0.0.24) (2021-06-11) ### [0.0.23](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.22...v0.0.23) (2021-06-10) ### [0.0.22](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.21...v0.0.22) (2021-06-10) ### [0.0.21](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.20...v0.0.21) (2021-06-10) ### [0.0.20](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.19...v0.0.20) (2021-06-10) ### [0.0.19](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.18...v0.0.19) (2021-06-10) ### [0.0.18](https://github.com/ECJ222/nuxt-page-visibility/compare/v0.0.17...v0.0.18) (2021-06-10) ### [0.0.17](https://github.com/ECJ222/page-visibility-module/compare/v0.0.16...v0.0.17) (2021-06-10) ### [0.0.16](https://github.com/ECJ222/page-visibility-module/compare/v0.0.15...v0.0.16) (2021-06-10) ### [0.0.15](https://github.com/ECJ222/page-visibility-module/compare/v0.0.14...v0.0.15) (2021-06-10) ### [0.0.14](https://github.com/ECJ222/page-visibility-module/compare/v0.0.13...v0.0.14) (2021-06-10) ### [0.0.13](https://github.com/ECJ222/page-visibility-module/compare/v0.0.12...v0.0.13) (2021-06-10) ### [0.0.12](https://github.com/ECJ222/page-visibility-module/compare/v0.0.10...v0.0.12) (2021-06-10) ### [0.0.9](https://github.com/ECJ222/page-visibility-module/compare/v0.0.10...v0.0.9) (2021-06-10) ### [0.0.9](https://github.com/ECJ222/page-visibility-module/compare/v0.0.10...v0.0.9) (2021-06-10) ### [0.0.10](https://github.com/ECJ222/page-visibility-module/compare/v0.0.9...v0.0.10) (2021-06-10) ### [0.0.9](https://github.com/ECJ222/page-visibility-module/compare/v0.0.8...v0.0.9) (2021-06-10) ### [0.0.8](https://github.com/ECJ222/page-visibility-module/compare/v0.0.7...v0.0.8) (2021-06-10) ### [0.0.7](https://github.com/ECJ222/page-visibility-module/compare/v0.0.6...v0.0.7) (2021-06-10) ### [0.0.6](https://github.com/ECJ222/page-visibility-module/compare/v0.0.4...v0.0.6) (2021-06-10) ### [0.0.5](https://github.com/ECJ222/page-visibility-module/compare/v0.0.4...v0.0.5) (2021-06-10) ### [0.0.4](https://github.com/ECJ222/page-visibility-module/compare/v0.0.3...v0.0.4) (2021-06-10) ### [0.0.3](https://github.com/ECJ222/page-visibility-module/compare/v0.0.2...v0.0.3) (2021-06-10) ### [0.0.2](https://github.com/ECJ222/page-visibility-module/compare/v0.0.1...v0.0.2) (2021-06-10) ### 0.0.1 (2021-06-10) ### Features * **lib:** add page visibility api ([6263c6d](https://github.com/ECJ222/page-visibility-module/commit/6263c6de1f32d394cfed3b2bc7b8711c3ef1f87b)) <file_sep>/README.md # 🌫️ nuxt-page-visibility [![npm version][npm-version-src]][npm-version-href] [![npm downloads][npm-downloads-src]][npm-downloads-href] [![License][license-src]][license-href] > A Nuxt.js module to detect page visibility ## Table of Contents - [Requirements](#requirements) - [Install](#install) - [Getting Started](#getting-started) - [Usage](#usage) - [License](#license) ## Requirements - npm - NuxtJS - NodeJS ## Install ```bash # npm $ npm install nuxt-page-visibility # yarn $ yarn add nuxt-page-visibility ``` ## Getting Started Add `'nuxt-page-visibility'` to the `modules` section of your `nuxt.config.js` file. ```js { modules: ["nuxt-page-visibility"]; } ``` ## Usage 1. Inject the module in your `nuxt.config.js` file. See [Getting Started](#getting-started). 2. `this.$visibility` is now available in your components. **Note** that `$visibility` returns an `object` with two properties one is `isVisible` which we would use to check if a user is focused on a page or not, While the other `isSupported` is used to check if the browser supports the Page Visibility API. ```js { ... watch: { $visibility: { handler (page) { if (page.isVisible) { // do something } else { // do something } }, deep: true } } ... } ``` ## License This project is licensed under [MIT](./LICENSE) <!-- Badges --> [npm-version-src]: https://img.shields.io/npm/v/nuxt-page-visibility/latest.svg [npm-version-href]: https://npmjs.com/package/nuxt-page-visibility [npm-downloads-src]: https://img.shields.io/npm/dt/nuxt-page-visibility.svg [npm-downloads-href]: https://npmjs.com/package/nuxt-page-visibility [license-src]: https://img.shields.io/npm/l/nuxt-page-visibility.svg [license-href]: https://npmjs.com/package/nuxt-page-visibility <file_sep>/lib/plugin.js import Vue from 'vue' import Visibility from './visibility' export default (context, inject) => { context.$visibility = Vue.observable(Visibility()) inject('visibility', context.$visibility) }
f2a888f66ec6b9dc098cf0ccf9766d9f0129b60f
[ "JavaScript", "Markdown" ]
5
JavaScript
ECJ222/nuxt-page-visibility
f044e2dc4ff37fadc9a52c01a961a9598b4e27a3
8345f40a2556f130cb0cc5116a14d9311bee19e5
refs/heads/master
<repo_name>GWSoT/StackBombing<file_sep>/StackBombing/Source.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include <windows.h> #include "Inject_and_Resume.h" #include "Procs_and_Threads.h" int main(int argc, char* argv[]) { WCHAR procName[] = L"explorer.exe"; DWORD pid = NameToPID((WCHAR*)procName); DWORD* threads = ListProcessThreads(pid); for (int i = 0; i < 20; i++) { inject(pid, threads[i]); Sleep(300); } free(threads); system("pause"); return 0; }
3fc1bbbb71e0536ec24b9483caa3c2f07c8b438b
[ "C++" ]
1
C++
GWSoT/StackBombing
f3e665e54e823784f2d34af649d48a8656a819ec
a6f8e315ca6ac86b78845ab0780a8b0fdb7534d2
refs/heads/master
<file_sep>module Photish module Plugin module Sshdeploy class Deploy def initialize(config, log) @config = config @log = log end def deploy_site log.info "Publishing website to #{host}" log.info "Cleaning temp locations and ensuring directories exist" execute("ssh #{host} -v '" + "mkdir -p #{publish_temp_dir} && " + "rm -rf #{publish_temp_dir}/* && " + "mkdir -p #{upload_temp_dir} && " + "rm -rf #{upload_temp_dir}/*" + "'") log.info "Creating tar gz of photish site" execute("GZIP=-9 tar -zcvf " + "#{output_dir_compress_file} " + "-C #{output_dir_with_base} .") log.info "Uploading site to upload temp location" execute("rsync -v " + "-e 'ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' " + "--progress #{output_dir_compress_file} " + "#{host}:#{upload_temp_dir}") log.info "Extracting site to publish temp location" execute("ssh #{host} -v " + "'tar -zxvf " + "#{upload_temp_dir}/#{output_dir_compress_filename} " + "-C #{publish_temp_dir}'") log.info "Moving publish temp to publish folder" execute("ssh #{host} -v " + "'sudo su #{www_user} bash -c \"" + "mkdir -p #{publish_dir} && " + "rm -rf #{publish_dir}/* && " + "cp -rf #{publish_temp_dir}/* #{publish_dir}\"'") log.info "#{Time.new}: Deployment complete" ensure FileUtils.rm_rf(output_dir_compress_file) end private attr_reader :config, :log delegate :deploy, :output_dir, :url, to: :config delegate :host, :publish_dir, :publish_temp_dir, :upload_temp_dir, :www_user, to: :deploy def output_dir_with_base File.join([output_dir, url.base].flatten) end def output_dir_compress_filename 'output_dir.tar.gz' end def output_dir_compress_file @output_dir_compress_file ||= File.join(Dir.mktmpdir, output_dir_compress_filename) end def self.is_for?(type) [ Photish::Plugin::Type::Deploy ].include?(type) end def self.engine_name 'ssh' end def execute(command) log.info "Executing: #{command}" system("#{command}") || exit(1) end end end end end <file_sep>module Photish module Plugin module Sshdeploy VERSION = "0.1.0" end end end <file_sep>require "photish/plugin/sshdeploy/version" require "photish/plugin/sshdeploy/deploy" module Photish module Plugin module Sshdeploy end end end <file_sep># Photish::Plugin::Sshdeploy This is a simple [Deployment Engine Plugin](https://github.com/henrylawson/photish#deployment-engine-plugins) for [Photish](https://github.com/henrylawson/photish#deploy) using SSH. ## Install To install it, simple include the Gem in your Gemfile: **./Gemfile** ```Gemfile gem 'photish-plugin-sshdeploy' ``` And in your Photish config, ensure it is listed in your `plugins` Config File Option. **./config.yml** ```YAML plugins: ['photish/plugin/sshdeploy'] ``` Then run `bundle install`. Now that it is installed, once you have configured it, use `photish deploy --engine=ssh` to run it. ## Configure This deployment engine requires certain values being present in your `config.yml` file. ```YAML deploy: host: foinq.com # the host to connect and deploy too publish_dir: /srv/www/foinq.com/photish-montage # the directory to copy files too publish_temp_dir: /tmp/photish-montage-publish # the temporary directory to extract files too upload_temp_dir: /tmp/photish-montage-upload # the temporary directory to upload files too www_user: www-fqc # the unix user account to finally copy the files under ``` It also requires that you have configured your `~/.ssh/config` file with the login details of the host you wish to upload too. [See here for a simple guide](http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/). ## Example usage An example usage can be seen in the [Photish Montage](https://github.com/henrylawson/photish-montage) demo. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
90f68d3059d029cc10ac847e03002cb3e75311a8
[ "Markdown", "Ruby" ]
4
Ruby
henrylawson/photish-plugin-sshdeploy
cf69df0171e1fe2259d7d077421ac5fdf73aabc3
374ff2ef779f252b5d7bfc26a352b4eea8a60003
refs/heads/master
<repo_name>yourdutchmedia/laravel-livewire-datatables<file_sep>/src/DatatableServiceProvider.php <?php namespace Ydm\Datatables; use Illuminate\Support\Facades\Blade; use Illuminate\View\Compilers\BladeCompiler; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; class DatatableServiceProvider extends PackageServiceProvider { public function bootingPackage() { $this->configureComponents(); } public function configurePackage(Package $package): void { $package->name('livewire-datatables') ->hasConfigFile() ->hasViews() ->hasTranslations(); } protected function configureComponents(): void { $this->callAfterResolving(BladeCompiler::class, function () { $this->registerComponent('table'); $this->registerComponent('table-td'); $this->registerComponent('table-th'); $this->registerComponent('table-tr'); }); } protected function registerComponent(string $component) { Blade::component('livewire-datatables::components.' . $component, 'ydm-' . $component); } } <file_sep>/src/DatatableComponent.php <?php namespace Ydm\Datatables; use Livewire\Component; use Ydm\Datatables\Traits\WithBulkActions; use Ydm\Datatables\Traits\WithCustomPagination; use Ydm\Datatables\Traits\WithFilters; use Ydm\Datatables\Traits\WithPerPagePagination; use Ydm\Datatables\Traits\WithSearch; use Ydm\Datatables\Traits\WithSorting; abstract class DatatableComponent extends Component { use WithBulkActions, WithCustomPagination, WithFilters, WithPerPagePagination, WithSearch, WithSorting; public $emptyMessage = 'No items found. Try narrowing your search.'; public $offlineIndicator = true; public $paginationTheme = 'tailwind'; public $refresh = false; protected $listeners = ['refreshDatatable' => '$refresh']; protected $pageName = 'page'; protected $queryString = [ 'filters' => ['except' => null], 'sorts' => ['except' => null], ]; protected $tableName = 'table'; public function __construct($id = null) { parent::__construct($id); $this->filters = array_merge($this->filters, $this->baseFilters); } protected function getColumn(string $column) { return collect($this->columns()) ->where('column', $column) ->first(); } public function getRowsProperty() { if ($this->paginationEnabled) { return $this->applyPagination($this->rowsQuery()); } return $this->rowsQuery()->get(); } public function render() { return view('livewire-datatables::datatable') ->with([ 'columns' => $this->columns(), 'rowView' => $this->rowView(), 'filtersView' => $this->filtersView(), 'customFilters' => $this->filters(), 'rows' => $this->rows, ]); } public function refreshAttribute(): string { if (is_numeric($this->refresh)) { return 'wire:poll.' . $this->refresh . 'ms'; } elseif (is_string($this->refresh)) { if ($this->refresh === '.keep-alive' || $this->refresh === 'keep-alive') { return 'wire:poll.keep-alive'; } elseif ($this->refresh === '.visible' || $this->refresh === 'visible') { return 'wire:poll.visible'; } return 'wire:poll="' . $this->refresh . '"'; } return ''; } public function resetAll(): void { $this->resetFilters(); $this->resetSearch(); $this->resetSorts(); $this->resetBulk(); $this->resetPage(); } public function rowsQuery() { $this->cleanFilters(); $query = $this->query(); if (method_exists($this, 'applySorting')) { $query = $this->applySorting($query); } if (method_exists($this, 'applySearchFilter')) { $query = $this->applySearchFilter($query); } return $query; } public function rowView(): string { return 'livewire-datatables::includes.table-row-columns'; } abstract public function columns(): array; abstract public function query(); } <file_sep>/src/Traits/WithBulkActions.php <?php namespace Ydm\Datatables\Traits; trait WithBulkActions { public $bulkActions = []; public $primaryKey = 'id'; public $selectPage = false; public $selectAll = false; public $selected = []; public function getSelectedKeysProperty(): array { return $this->selectedKeys(); } public function getSelectedRowsQueryProperty() { return $this->selectedRowsQuery(); } public function renderingWithBulkActions(): void { if ($this->selectAll) { $this->selectPageRows(); } } public function selectedKeys(): array { return $this->selectedRowsQuery()->pluck($this->rowsQuery()->qualifyColumn($this->primaryKey))->toArray(); } public function selectAll(): void { $this->selectAll = true; } public function selectPageRows(): void { $this->selected = $this->rows->pluck($this->primaryKey)->map(fn($key) => (string)$key); } public function selectedRowsQuery() { return (clone $this->rowsQuery()) ->unless($this->selectAll, function ($query) { return $query->whereIn($query->qualifyColumn($this->primaryKey), $this->selected); }); } public function resetBulk(): void { $this->selectPage = false; $this->selectAll = false; $this->selected = []; } public function updatedSelected(): void { $this->selectAll = false; $this->selectPage = false; } public function updatedSelectPage($value): void { if ($value) { $this->selectPageRows(); return; } $this->selectAll = false; $this->selected = []; } } <file_sep>/src/Traits/WithSearch.php <?php namespace Ydm\Datatables\Traits; trait WithSearch { public $searchFilterDebounce = null; public $searchFilterDefer = null; public $searchFilterLazy = null; public $showSearch = true; public function getSearchFilterOptionsProperty(): string { if ($this->searchFilterDebounce) { return '.debounce.' . $this->searchFilterDebounce . 'ms'; } if ($this->searchFilterDefer) { return '.defer'; } if ($this->searchFilterLazy) { return '.lazy'; } return ''; } public function resetSearch(): void { $this->filters['search'] = null; } } <file_sep>/src/Support/Column.php <?php namespace Ydm\Datatables\Support; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Query\Builder; use Illuminate\Support\Str; class Column { public $class; public $column; public $text; public $blank = false; public $hidden = false; public $html = false; public $searchable = false; public $sortable = false; public $formatCallback; public $searchCallback; public $sortCallback; public static function blank(): Column { return new static(null, null); } public static function columnsFromBuilder($queryBuilder = null): ?array { if ($queryBuilder instanceof EloquentBuilder) { return $queryBuilder->getQuery()->columns; } if ($queryBuilder instanceof Builder) { return $queryBuilder->columns; } return null; } public static function hasMatch($column, $searchColumns): bool { return in_array($column, $searchColumns ?? [], true); } public static function hasRelation($column): bool { return Str::contains($column, '.'); } public static function hasWildcardMatch($column, $searchColumns): bool { return count(array_filter($searchColumns ?? [], function ($searchColumn) use ($column) { $hasWildcard = Str::endsWith($searchColumn, '*'); if (!$hasWildcard) { return false; } if (!self::hasRelation($column)) { return true; } $selectColumnPrefix = self::parseRelation($searchColumn); $columnPrefix = self::parseRelation($column); return $selectColumnPrefix === $columnPrefix; })) > 0; } public static function mapToSelected($column, $queryBuilder): ?string { $select = self::columnsFromBuilder($queryBuilder); if (is_null($select)) { return null; } // Search builder select for a match $hasMatch = self::hasMatch($column, $select); if ($hasMatch) { return $column; } // Search builder select for a wildcard match $hasWildcardMatch = self::hasWildcardMatch($column, $select); if ($hasWildcardMatch) { return $column; } // Split the relation and field $hasRelation = self::hasRelation($column); $relationName = self::parseRelation($column); $fieldName = self::parseField($column); if (!$hasRelation) { return null; } if ($queryBuilder instanceof EloquentBuilder) { $relation = $queryBuilder->getRelation($relationName); $possibleTable = $relation->getModel()->getTable(); } elseif ($queryBuilder instanceof Builder) { $possibleTable = null; } else { $possibleTable = null; } if (!is_null($possibleTable)) { $possibleSelectColumn = $possibleTable . '.' . $fieldName; $possibleMatch = self::hasMatch($possibleSelectColumn, $select); if ($possibleMatch) { return $possibleSelectColumn; } $possibleWildcardMatch = self::hasWildcardMatch($possibleSelectColumn, $select); if ($possibleWildcardMatch) { return $possibleSelectColumn; } } return null; } public static function make(string $text = null, string $column = null): Column { return new static($text, $column); } public static function parseField($column): string { return Str::afterLast($column, '.'); } public static function parseRelation($column): string { return Str::beforeLast($column, '.'); } public function __construct(string $text = null, string $column = null) { $this->text = $text; if (!$column && $text) { $this->column = Str::snake($text); } else { $this->column = $column; } if (!$this->column && !$this->text) { $this->blank = true; } } public function addClass(string $class): Column { $this->class = $class; return $this; } public function class(): ?string { return $this->class; } public function column(): ?string { return $this->column; } public function format(callable $callable): Column { $this->formatCallback = $callable; return $this; } public function formatted($row, $column = null) { if ($column instanceof self) { $columnName = $column->column(); } elseif (is_string($column)) { $columnName = $column; } else { $columnName = $this->column(); } $value = data_get($row, $columnName); if ($this->formatCallback) { return app()->call($this->formatCallback, ['value' => $value, 'column' => $column, 'row' => $row]); } return $value; } public function getSearchCallback(): ?callable { return $this->searchCallback; } public function getSortCallback(): ?callable { return $this->sortCallback; } public function hasSearchCallback(): bool { return $this->searchCallback !== null; } public function hasSortCallback(): bool { return $this->sortCallback !== null; } public function hideIf(bool $condition): Column { $this->hidden = $condition; return $this; } public function html(): Column { $this->html = true; return $this; } public function isBlank(): bool { return $this->blank === true; } public function isSearchable(): bool { return $this->searchable === true; } public function isSortable(): bool { return $this->sortable === true; } public function isVisible(): bool { return $this->hidden !== true; } public function searchable(callable $callback = null): Column { $this->searchable = true; $this->searchCallback = $callback; return $this; } public function sortable($callback = null): Column { $this->sortable = true; $this->sortCallback = $callback; return $this; } public function text(): ?string { return $this->text; } } <file_sep>/src/Support/Filter.php <?php namespace Ydm\Datatables\Support; class Filter { public const TYPE_SELECT = 'select'; public $name; public $options = []; public $type; public static function make(string $name): Filter { return new static($name); } public function __construct(string $name) { $this->name = $name; } public function isSelect(): bool { return $this->type === self::TYPE_SELECT; } public function name(): string { return $this->name; } public function options(): array { return $this->options; } public function select(array $options = []): Filter { $this->type = self::TYPE_SELECT; $this->options = $options; return $this; } }
155b88bd442323366cc8fb6e0a9e246611f24a41
[ "PHP" ]
6
PHP
yourdutchmedia/laravel-livewire-datatables
168a571f92393deba803771b6ebbcc77483cb7e3
b1cf2b173f299c2ead9aa9efe9dc15ff2daa7645
refs/heads/main
<file_sep>import React from 'react'; import Layout from '../components/layout/Layout'; import Register from '../components/auth/Register'; const RegisterPage = () => { return ( <Layout> <Register /> </Layout> ); }; export default RegisterPage; <file_sep>import Room from '../models/room'; import ErrorHandler from '../utils/errorHandler'; import catchAsync from '../middlewares/catchAsyncErrors'; import APIFeatures from '../utils/apiFeatures'; // @route POST /api/rooms // @desc Create new Room // @access Private const createRoom = catchAsync(async (req, res, next) => { const room = await Room.create(req.body); res.status(200).json({ success: true, room }); }); // @route GET /api/rooms // @desc Fetch all Rooms // @access Public const allRooms = catchAsync(async (req, res, next) => { const resPerPage = 4; const roomsCount = await Room.countDocuments(); const apiFeatures = new APIFeatures(Room.find(), req.query).search().filter(); let rooms = await apiFeatures.query; let filteredRoomsCount = rooms.length; apiFeatures.pagination(resPerPage); rooms = await apiFeatures.query; res.status(200).json({ success: true, roomsCount, resPerPage, filteredRoomsCount, rooms, }); }); // @route GET /api/rooms/:id // @desc Get Single Room // @access Public const getRoom = catchAsync(async (req, res, next) => { const room = await Room.findById(req.query.id); if (!room) { return next(new ErrorHandler('Room does not exist', 404)); } res.status(200).json({ success: true, room }); }); // @route PUT /api/rooms/:id // @desc UPDATE Room // @access PRIVATE const updateRoom = catchAsync(async (req, res, next) => { let room = await Room.findById(req.query.id); if (!room) { return next(new ErrorHandler('Room does not exist', 404)); } room = await Room.findByIdAndUpdate(req.query.id, req.body, { new: true, runValidators: true, useFindAndModify: false, }); res.status(200).json({ success: true, room }); }); // @route DELETE /api/rooms/:id // @desc Delete Room // @access PRIVATE const deleteRoom = catchAsync(async (req, res, next) => { const room = await Room.findById(req.query.id); if (!room) { return next(new ErrorHandler('Room does not exist', 404)); } await Room.remove(); res .status(200) .json({ success: true, message: 'Room was successfully removed' }); }); export { allRooms, createRoom, getRoom, updateRoom, deleteRoom }; <file_sep>import React from 'react'; const RoomFeatures = ({ guestCapacity, numOfBeds, breakfast, internet, airConditioned, petsAllowed, roomCleaning, }) => { return ( <div className='features mt-5'> <h3 className='mb-4'>Features:</h3> <div className='room-feature'> <i className='fa fa-cog fa-fw fa-users' aria-hidden='true'></i> <p>{guestCapacity} Guests</p> </div> <div className='room-feature'> <i className='fa fa-cog fa-fw fa-bed' aria-hidden='true'></i> <p>{numOfBeds} Beds</p> </div> <div className='room-feature'> <i className={ breakfast ? 'fa fa-check text-success' : 'fa fa-times text-danger' } aria-hidden='true' ></i> <p>Breakfast</p> </div> <div className='room-feature'> <i className={ internet ? 'fa fa-check text-success' : 'fa fa-times text-danger' } aria-hidden='true' ></i> <p>Internet</p> </div> <div className='room-feature'> <i className={ airConditioned ? 'fa fa-check text-success' : 'fa fa-times text-danger' } aria-hidden='true' ></i> <p>Air Conditioned</p> </div> <div className='room-feature'> <i className={ petsAllowed ? 'fa fa-check text-success' : 'fa fa-times text-danger' } aria-hidden='true' ></i> <p>Pets Allowed</p> </div> <div className='room-feature'> <i className={ roomCleaning ? 'fa fa-check text-success' : 'fa fa-times text-danger' } aria-hidden='true' ></i> <p>Room Cleaning</p> </div> </div> ); }; export default RoomFeatures; <file_sep>export const ALL_ROOMS_SUCCESS = 'ALL_ROOMS_SUCCESS'; export const ALL_ROOMS_FAILED = 'ALL_ROOMS_FAILED'; export const ROOMS_DETAILS_SUCCESS = 'ROOMS_DETAILS_SUCCESS'; export const ROOMS_DETAILS_FAILED = 'ROOMS_DETAILS_FAILED'; export const CLEAR_ERRORS = 'CLEAR_ERRORS'; <file_sep>module.exports = { env: { DB_LOCAL_URI: 'mongodb://localhost:27017/bookit', CLOUDINARY_CLOUD_NAME: 'awais512', CLOUDINARY_API_KEY: '664727195549493', CLOUDINARY_SECRET_KEY: 'CLOUDINARY_URL=cloudinary://664727195549493:FKnl48TdaY6sWCyEAQIwJwUqzbg@awais512', }, images: { domains: ['res.cloudinary.com'], }, }; <file_sep>import { REGISTER_USER_REQUEST, REGISTER_USER_SUCCESS, REGISTER_USER_FAIL, CLEAR_ERRORS, } from '../constants/userConstants'; export const authReducer = (state = { user: null }, action) => { switch (action.type) { case REGISTER_USER_REQUEST: return { loading: true, }; case REGISTER_USER_SUCCESS: return { loading: false, success: true, }; case REGISTER_USER_FAIL: return { loading: false, error: action.payload, }; case CLEAR_ERRORS: return { ...state, error: null, }; default: return state; } }; <file_sep>import User from '../models/user'; import ErrorHandler from '../utils/errorHandler'; import catchAsyncErrors from '../middlewares/catchAsyncErrors'; import cloudinary from 'cloudinary'; //Setting up cloudinary config cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); // @route POST /api/rooms // @desc Create new Room // @access Private // Register user => /api/auth/register const registerUser = catchAsyncErrors(async (req, res) => { const result = await cloudinary.v2.uploader.upload(req.body.avatar, { folder: 'bookit/avatars', width: '150', crop: 'scale', }); const { name, email, password } = req.body; const user = await User.create({ name, email, password, avatar: { public_id: result.public_id, url: result.secure_url, }, }); res.status(200).json({ success: true, message: 'Account Registered successfully', }); }); export { registerUser };
65f19b624047b68966d6da9db714507897b705fc
[ "JavaScript" ]
7
JavaScript
Awais512/bookit
eee0a3305b139372a90fc58e1e6964204c0061d7
4c7c80d94874d488f70476d164c25376969b2767
refs/heads/master
<repo_name>ReadyPlayerEmma/ShulkerRespawner<file_sep>/1.13/src/com/github/joelgodofwar/sr/ShulkerRespawner.java package com.github.joelgodofwar.sr; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Biome; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Enderman; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.entity.Shulker; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import com.github.joelgodofwar.sr.api.Ansi; public class ShulkerRespawner extends JavaPlugin implements Listener{ public final static Logger logger = Logger.getLogger("Minecraft"); public static String daLang; public static boolean UpdateCheck; public static boolean debug; File langFile; FileConfiguration lang; public String updateurl = "https://raw.githubusercontent.com/JoelGodOfwar/ShulkerRespawner/master/versions/1.13/version.txt"; @Override // TODO: onEnable public void onEnable(){ daLang = getConfig().getString("lang"); debug = getConfig().getBoolean("debug"); langFile = new File(getDataFolder(), "lang.yml"); if(!langFile.exists()){ // checks if the yaml does not exist langFile.getParentFile().mkdirs(); // creates the /plugins/<pluginName>/ directory if not found saveResource("lang.yml", true); //ConfigAPI.copy(getResource("lang.yml"), langFile); // copies the yaml from your jar to the folder /plugin/<pluginName> } lang = new YamlConfiguration(); try { lang.load(langFile); } catch (IOException | InvalidConfigurationException e1) { e1.printStackTrace(); } /** DEV check **/ File jarfile = this.getFile().getAbsoluteFile(); if(jarfile.toString().contains("-DEV")){ debug = true; log("jarfile contains dev, debug set to true."); } getServer().getPluginManager().registerEvents(this, this); consoleInfo(Ansi.Bold + "ENABLED" + Ansi.SANE); if(getConfig().getBoolean("debug")==true&&!(jarfile.toString().contains("-DEV"))){ logDebug("Config.yml dump"); logDebug("auto_update_check=" + getConfig().getBoolean("auto_update_check")); logDebug("debug=" + getConfig().getBoolean("debug")); logDebug("lang=" + getConfig().getString("lang")); } } @Override // TODO: onDisable public void onDisable(){ consoleInfo(Ansi.Bold + "DISABLED" + Ansi.SANE); } public void consoleInfo(String state) { PluginDescriptionFile pdfFile = this.getDescription(); logger.info(Ansi.YELLOW + "**************************************" + Ansi.SANE); logger.info(Ansi.GREEN + pdfFile.getName() + " v" + pdfFile.getVersion() + Ansi.SANE + " is " + state); logger.info(Ansi.YELLOW + "**************************************" + Ansi.SANE); } public void log(String dalog){ logger.info(Ansi.YELLOW + "" + this.getName() + Ansi.SANE + " " + dalog + Ansi.SANE); } public void logDebug(String dalog){ log(" " + this.getDescription().getVersion() + Ansi.RED + Ansi.Bold + " [DEBUG] " + Ansi.SANE + dalog); } public void logWarn(String dalog){ log(" " + this.getDescription().getVersion() + Ansi.RED + Ansi.Bold + " [WARNING] " + Ansi.SANE + dalog); } @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent event) { Player p = event.getPlayer(); if(p.isOp() && UpdateCheck){ try { URL url = new URL(updateurl); final URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final String localVersion = this.getDescription().getVersion(); if(debug){log("response= ." + response + ".");} //TODO: Logger if(debug){log("localVersion= ." + localVersion + ".");} //TODO: Logger if (!response.equalsIgnoreCase(localVersion)) { p.sendMessage(ChatColor.YELLOW + this.getName() + ChatColor.RED + " " + lang.get("newversion." + daLang + "")); } } catch (MalformedURLException e) { log("MalformedURLException"); e.printStackTrace(); } catch (IOException e) { log("IOException"); e.printStackTrace(); }catch (Exception e) { log("Exception"); e.printStackTrace(); } } if(p.getDisplayName().equals("JoelYahwehOfWar")||p.getDisplayName().equals("JoelGodOfWar")){ p.sendMessage(this.getName() + " " + this.getDescription().getVersion() + " Hello father!"); } } @EventHandler public void onCreatureSpawn(CreatureSpawnEvent e){ //onEntitySpawn(EntitySpawnEvent e) { Entity entity = e.getEntity(); if(debug){log("entity=" + entity.getType());} if (entity instanceof Enderman){ log("test"); if(debug){logDebug("biome=" + entity.getWorld().getEnvironment().toString());} //if(entity.getWorld().getEnvironment() == Environment.THE_END){ if(entity.getWorld().getEnvironment() == Environment.THE_END&&(entity.getLocation().getBlock().getBiome() == Biome.END_HIGHLANDS||entity.getLocation().getBlock().getBiome() == Biome.END_MIDLANDS)){ if(debug){logDebug("block=" + entity.getLocation().getBlock().getType().toString());} if(entity.getLocation().subtract(0, 1, 0).getBlock().getType().toString().contains("PURPUR")||entity.getLocation().getBlock().getType().toString().contains("PURPUR")){ Location location = entity.getLocation(); World world = entity.getWorld(); e.setCancelled(true); log("Enderman tried to spawn at " + location + " and a shulker was spawned in it's place."); world.spawn(location, Shulker.class); } } } } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){ //Player p = (Player)sender; if (cmd.getName().equalsIgnoreCase("SR")){ if (args.length == 0) { /** Check if player has permission */ Player player = null; if (sender instanceof Player) { player = (Player) sender; if (!player.hasPermission("shulkerrespawner.op") && !player.isOp()) { player.sendMessage(ChatColor.DARK_RED + "" + lang.get("noperm." + daLang + "")); return true; } } /** Command code */ sender.sendMessage(ChatColor.GREEN + "[]===============[" + ChatColor.YELLOW + "ShulkerRespawner" + ChatColor.GREEN + "]===============[]"); if(sender.isOp()||sender.hasPermission("shulkerrespawner.op")){ sender.sendMessage(ChatColor.GOLD + " OP Commands"); sender.sendMessage(ChatColor.GOLD + " /SR DEBUG true/false - " + lang.get("srdebuguse." + daLang + "")); }else{ sender.sendMessage(ChatColor.GOLD + "" + lang.get("noperm." + daLang + "")); } sender.sendMessage(ChatColor.GREEN + "[]===============[" + ChatColor.YELLOW + "ShulkerRespawner" + ChatColor.GREEN + "]===============[]"); return true; } if(args[0].equalsIgnoreCase("DEBUG")){ if(args.length< 1){ return false; } /** Check if player has permission */ Player player = null; if (sender instanceof Player) { player = (Player) sender; if (!player.hasPermission("shulkerrespawner.op") && !player.isOp()) { player.sendMessage(ChatColor.DARK_RED + "" + lang.get("noperm." + daLang + "")); return true; } } /** Command code */ if(!args[1].equalsIgnoreCase("true") & !args[1].equalsIgnoreCase("false")){ sender.sendMessage(ChatColor.YELLOW + this.getName() + " §c" + lang.get("boolean." + daLang + "") + ": /SR DEBUG True/False"); }else if(args[1].contains("true") || args[1].contains("false")){ //sender.sendMessage(ChatColor.YELLOW + this.getName() + " " + " " + args[1]); if(args[1].contains("false")){ debug = false; sender.sendMessage(ChatColor.YELLOW + this.getName() + " " + lang.get("debugfalse." + daLang + "")); }else if(args[1].contains("true")){ debug = true; sender.sendMessage(ChatColor.YELLOW + this.getName() + " " + lang.get("debugtrue." + daLang + "")); } return true; } } } return false; } public static String getMCVersion() { String strVersion = Bukkit.getVersion(); strVersion = strVersion.substring(strVersion.indexOf("MC: "), strVersion.length()); strVersion = strVersion.replace("MC: ", "").replace(")", ""); return strVersion; } }
540acd961e80b498be74ec05bea4f8caf5860191
[ "Java" ]
1
Java
ReadyPlayerEmma/ShulkerRespawner
9cf08e0c965518697446c7badefe2352094b5668
428df507a5138b50532e9c079afd835c0c840c02
refs/heads/master
<repo_name>Zee604/Room-DataBase-Android-App<file_sep>/README.md # Room-DataBase-Android-App A simple android application using room database. Insert,Delete,update built in queries. <file_sep>/app/src/main/java/com/ashish/roomdemo/constants/Constants.java package com.ashish.roomdemo.constants; public class Constants { public static final String UPDATE_Person_Id = "update_task"; }
2e818c2adbe37328043fb9230a7829ba6fa508f2
[ "Markdown", "Java" ]
2
Markdown
Zee604/Room-DataBase-Android-App
78321fe3b8a857a2342f365a4245280a9f6a5fbb
bb0ac3ab502891bf4ea64788ae9e93feeeeffe1d
refs/heads/master
<repo_name>brownman/install_config_test<file_sep>/fix/locals.sh ubuntu1304(){ # Set the locale sudo locale-gen en_US.UTF-8 export LANG=en_US.UTF-8 export LANGUAGE=en_US:en export LC_ALL=en_US.UTF-8 #RUN echo 'LC_ALL="en_US.UTF-8"' >> /etc/default/locale #RUN locale-gen en_US.UTF-8 #RUN update-locale LANG=en_US.UTF-8 } install(){ ubuntu1304 } config(){ trace } test_install(){ trace } test_config(){ trace } commander $@ <file_sep>/install/ruby.sh #NOTE: we have to add /etc/rsyslog.conf using Dockerfile:ADD command #http://dockerfile.github.io/#/ruby # https://gitlab.com/gitlab-org/gitlab-ci-runner/ #https://gist.github.com/Gurpartap/ef78033f059cf593e4f0 set -u ruby_env(){ # install ruby, bundler export INSTALL_RUBY_VERSION=2.1.0 export RBENV_ROOT=${HOME}/.rbenv export PATH=${RBENV_ROOT}/bin:${PATH} wget -qO - https://raw.github.com/fesplugas/rbenv-installer/master/bin/rbenv-installer | bash rbenv install $INSTALL_RUBY_VERSION rbenv global $INSTALL_RUBY_VERSION echo "eval \"\$(rbenv init -)\"" | sudo tee /root/.profile . /root/.profile gem install bundler } install_gitlab_repo(){ #NEEDED: curl local dir="$dir_gitlab_ci_runner_repo" mkdir1 $dir cd /tmp curl --silent -L https://gitlab.com/gitlab-org/gitlab-ci-runner/repository/archive.tar.gz | tar xz mv /tmp/gitlab-ci-runner.git $dir cd $dir ( bundle install --deployment ) || { trace error on using bundler; } } ensure_bundler_exist(){ ensure type bundler ensure whereis bundler ensure which bundler } install(){ #mute install_ruby_ubuntu ruby_env #mute travis_only } config(){ # trace install_bundler #trace install_gitlab_repo trace } test_install(){ trace } test_config(){ trace # ensure_bundler_exist } commander $@ <file_sep>/bash/caller.sh export str_caller1='eval echo $(caller)' export str_caller2='echo $(caller)' func2(){ $str_caller1 $str_caller2 eval "$str_caller1" eval "$str_caller2" } func1(){ func2 } func1 <file_sep>/install/mean.sh set -u set -e # NOTE : Permission of myApp is 777 set_env1(){ # mkdir1 $dir_my_app mkdir1 $dir_nodejs SUDO='' } node1(){ cd /tmp && \ wget http://nodejs.org/dist/node-latest.tar.gz && \ tar xvzf node-latest.tar.gz && \ rm -f node-latest.tar.gz && \ cd node-v* && \ ./configure && \ CXX="g++ -Wno-unused-local-typedefs" make && \ CXX="g++ -Wno-unused-local-typedefs" make install && \ cd /tmp && \ mv /tmp/node-v* /tmp/nodejs && \ npm install -g npm && \ echo '\n# Node.js\nexport PATH="node_modules/.bin:$PATH"' >> /root/.bashrc } node0(){ # cd $dir # apt1 curl sudo apt-get install -y curl #install only if not-already installed cd /tmp curl http://nodejs.org/dist/v0.10.26/node-v0.10.26-linux-x64.tar.gz | tar xz mv /tmp/node* $dir_nodejs $SUDO ln -s $dir_nodejs/bin/node /usr/bin/node $SUDO ln -s $dir_nodejs/bin/npm /usr/bin/npm } npm1(){ $SUDO npm update -g npm $SUDO npm install -g grunt-cli bower $SUDO npm install -g mean-cli@${VER_MEAN_CLI} } scaffold(){ #grunt test cd $path_my_app mean init $APP_NAME cd $dir_my_app; $SUDO npm install -g | pv trace $SUDO npm link } #cmd_start="${1:-before}" #eval "$cmd_start" install(){ node1 } config(){ #env | grep opt npm1 | pv scaffold | pv trace } test_install(){ #ensure "test -L $PATH_BIN/npm" #ensure "test -L $PATH_BIN/node" #ensure which npm #ensure whereis npm #ensure npm #ensure sudo npm trace } test_config(){ # test -d $dir_my_app # ls $dir_my_app trace ls -l $dir_my_app # cd $dir_my_app # ( grunt test ) || { trace imagine all tests are passing!; } } test_install(){ trace } set_env1 commander $@ <file_sep>/install/rsyslog.sh rsyslog1(){ export DEBIAN_FRONTEND=noninteractive sed -i 's/# \(.*multiverse$\)/\1/g' /etc/apt/sources.list && \ apt-get -y update apt-get -y -q install software-properties-common python-software-properties add-apt-repository -y ppa:adiscon/v8-stable apt-get -y update apt-get -y -q install rsyslog sed 's/#$ModLoad imudp/$ModLoad imudp/' -i /etc/rsyslog.conf sed 's/#$UDPServerRun 514/$UDPServerRun 514/' -i /etc/rsyslog.conf sed 's/#$ModLoad imtcp/$ModLoad imtcp/' -i /etc/rsyslog.conf sed 's/#$InputTCPServerRun 514/$InputTCPServerRun 514/' -i /etc/rsyslog.conf } <file_sep>/.old/run.sh #!/bin/bash /usr/sbin/sshd -D & LC_ALL=C.UTF-8 sudo -H -u mongodb mongod --nojournal & cd /home/mean/myApp ; sleep 5s ; sudo -u mean node server.js <file_sep>/install/sources.sh install(){ add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe restricted multiverse" } commander $@ <file_sep>/.old/install/ruby.sh ruby1(){ #machine dependencies # apt-get update && \ # apt-get -y upgrade # \ # apt-get install -y build-essential && \ # apt-get install -y software-properties-common && \ # apt-get install -y byobu curl git htop man unzip vim wget && \ # rm -rf /var/lib/apt/lists/* # Install Ruby. # apt-get update && \ apt-get install -y ruby ruby-dev ruby-bundler && \ rm -rf /var/lib/apt/lists/* } ruby22(){ sudo apt-get update -y sudo apt-get install -y curl wget curl gcc libxml2-dev libxslt-dev libcurl4-openssl-dev libreadline6-dev libc6-dev libssl-dev make build-essential zlib1g-dev openssh-server git-core libyaml-dev postfix libpq-dev libicu-dev mkdir /tmp/ruby && cd /tmp/ruby curl --progress ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p353.tar.gz | tar xz cd ruby-2.0.0-p353 ./configure --prefix=$dir_base --disable-install-rdoc --disable-install-ri make make install #gem install bundler } ruby21(){ sudo apt-get update -qq && \ apt-get install -y make curl -qq && \ apt-get clean && \ curl -sSL "https://github.com/postmodern/ruby-install/archive/master.tar.gz" -o /tmp/ruby-install-master.tar.gz && \ cd /tmp && tar -zxvf ruby-install-master.tar.gz && \ cd /tmp/ruby-install-master && make install && \ apt-get update && \ echo "gem: --no-rdoc --no-ri" >> ~/.gemrc && \ ruby-install -i /usr/local/ ruby -- --disable-install-rdoc --disable-install-ri && \ gem update --system && \ gem install bundler } # Update your packages and install the ones that are needed to compile Ruby # Download Ruby and compile it # don't install ruby rdocs or ri: install_bundler(){ #echo "gem: --no-rdoc --no-ri" | sudo tee /usr/local/etc/gemrc echo "gem: --no-rdoc --no-ri" | tee $HOME/.gemrc gem install bundler } travis_only(){ #or if machine is 12.04 sudo apt-get update sudo apt-get install ruby1.9.1 ruby1.9.1-dev \ rubygems1.9.1 irb1.9.1 ri1.9.1 rdoc1.9.1 \ build-essential libopenssl-ruby1.9.1 libssl-dev zlib1g-dev sudo update-alternatives --install /usr/bin/ruby ruby /usr/bin/ruby1.9.1 400 \ --slave /usr/share/man/man1/ruby.1.gz ruby.1.gz \ /usr/share/man/man1/ruby1.9.1.1.gz \ --slave /usr/bin/ri ri /usr/bin/ri1.9.1 \ --slave /usr/bin/irb irb /usr/bin/irb1.9.1 \ --slave /usr/bin/rdoc rdoc /usr/bin/rdoc1.9.1 # choose your interpreter # changes symlinks for /usr/bin/ruby , /usr/bin/gem # /usr/bin/irb, /usr/bin/ri and man (1) ruby sudo update-alternatives --config ruby sudo update-alternatives --config gem # now try ruby --version } ruby19(){ sudo apt-get update -y sudo apt-get install -y wget curl gcc libxml2-dev libxslt-dev libcurl4-openssl-dev libreadline6-dev libc6-dev libssl-dev make build-essential zlib1g-dev openssh-server git-core libyaml-dev postfix libpq-dev libicu-dev mkdir /tmp/ruby cd /tmp/ruby curl --progress http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p392.tar.gz | tar xz cd /tmp/ruby/ruby-1.9.3-p392 ./configure --disable-install-rdoc make sudo make install } install_ruby_ubuntu(){ #https://www.ruby-lang.org/en/installation/ sudo apt-get install -y ruby-full curl } <file_sep>/.old/install/add_user.sh # Create a mean user mkdir -p /home/mean useradd mean -d /home/mean -s /bin/bash cd /home/mean chown mean:mean /home/mean echo "user creation completed" <file_sep>/install/ssh.sh #RUN mkdir /var/run/sshd #RUN echo 'root:mean22' | chpasswd #SSHD install(){ sudo apt-get install -y openssh-server } config(){ trace '' # commander sudo service sshd start #sudo mkdir -p /var/run/sshd #echo 'root:root' | sudo tee chpasswd #sudo su root <<START #START #sudo sed -i "s/session.*required.*pam_loginuid.so/#session required pam_loginuid.so/" /etc/pam.d/sshd #sudo sed -i "s/PermitRootLogin without-password/#PermitRootLogin without-password/" /etc/ssh/sshd_config } test_install(){ trace } test_config(){ ( sudo netstat -ntlp | grep ssh ) || { trace imagine sshd is working; } } commander $@ <file_sep>/bashism.sh middle=mkdir1 source config.cfg step1(){ local file="bash/${middle}.sh" commander chmod +x $file commander $file } step1 <file_sep>/travis.sh #!/usr/bin/env bash toilet --gay "I'm: $(whoami)" where_am_i () { local file=${1:-"${BASH_SOURCE[1]}"}; local rpath=$(readlink -m $file); local rcommand=${rpath##*/}; local str_res=${rpath%/*}; local dir_self="$( cd $str_res && pwd )"; echo "$dir_self" } pushd `where_am_i $0` >/dev/null set -u export RUN=$1 set_env(){ source config.cfg ############################################## decide: MODE_DEBUG set_mode permission_fix env1 ############################################## chmod u+x install/*.sh } step(){ set -e set -u local line=$1 toilet --gay $line print_func $line print_title INSTALL commander install/${line}.sh install; print_title TEST_INSTALL commander install/${line}.sh test_install; print_title CONFIG commander install/${line}.sh config; print_title TEST_CONFIG commander install/${line}.sh test_config; } steps(){ #install ubuntu packages while read line;do test -n "$line" || break step $line done < <( cat list.txt ) } set_env if [ $RUN = all ];then steps else step $RUN fi #install #step config #step test popd >/dev/null <file_sep>/install/apt.sh #must install package sudo on Dockerfile #RUN apt-get install -y -q #openssh-server sudo curl search1(){ apt-cache search fortune } update1(){ sudo apt-get -y update } add_apt_repository1(){ sudo apt-get install -y python-software-properties } sources1(){ sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe restricted multiverse" } ppa1(){ sudo add-apt-repository -y ppa:git-core/ppa } apt1(){ while read line;do commander "sudo apt-get install -y -q ${line}" done <<START cowsay pv toilet build-essential gcc git git-core libcurl4-openssl-dev libicu-dev libpq-dev libreadline-dev libreadline-gplv2-dev libssl-dev libxml2 libxml2-dev libxslt1-dev libxslt-dev libyaml-dev logrotate lsb-release make net-tools postfix pwgen python-software-properties software-properties-common sudo supervisor tklib unzip wget zlib1g-dev START } install(){ add_apt_repository1 sources1 ppa1 update1 search1 apt1 } config(){ which cowsay whereis cowsay } test_install(){ /usr/games/cowsay hi echo 'great!' | /usr/games/cowsay -f $(ls /usr/share/cowsay/cows/ | shuf -n1) } test_config(){ trace } commander $@ <file_sep>/README.md - [BUILD ERR](https://registry.hub.docker.com/u/brownman/install-config-test/builds_history/94705/) [![Build Status](https://travis-ci.org/brownman/install_config_test.svg?branch=master)](https://travis-ci.org/brownman/install_config_test) [![Circle CI](https://circleci.com/gh/brownman/install_config_test.svg?style=svg)](https://circleci.com/gh/brownman/install_config_test) gitlabci-runner-nodejs-docker ============================= nodejs npm bower grunt-cli redis mongodb docker tips: ------ - http://www.centurylinklabs.com/15-quick-docker-tips/ - http://handsonwith.com/ - https://coderwall.com/trending?search=%23docker - http://stackoverflow.com/tags - https://github.com/tianon/dockerfiles - https://gitlab.com/gitlab-org/gitlab-ci/blob/master/doc/install/installation.md - http://dockerfile.github.io/#/nodejs - https://blog.logentries.com/2014/03/how-to-run-rsyslog-in-a-docker-container-for-logging/ - https://github.com/jplock/docker-rsyslog/blob/master/Dockerfile faster testing: ==== use 1 docker container as the base image: install packages + create dir-structure! use 1 docker container to config/run/test ! [link](http://dockerfile.github.io/#/ruby-runtime) <file_sep>/.old/install/apt.sh ###################################### ###################################### source.list RUN echo "deb http://il.archive.ubuntu.com/ubuntu $(lsb_release -sc) main universe" > /etc/apt/sources.list && \ echo "deb http://il.archive.ubuntu.com/ubuntu $(lsb_release -sc)-updates main universe" >> /etc/apt/sources.list echo "DEBIAN_FRONTEND: $DEBIAN_FRONTEND" export DEBIAN_FRONTEND=noninteractive echo "DEBIAN_FRONTEND: $DEBIAN_FRONTEND" sudo apt-get -y update sudo apt-get -y upgrade export list_apt="wget \ curl \ gcc \ libxml2-dev \ libxslt-dev \ libcurl4-openssl-dev \ libreadline6-dev \ libc6-dev \ libssl-dev \ make \ build-essential \ zlib1g-dev \ openssh-server \ git-core \ libyaml-dev \ postfix \ libicu-dev \ libfreetype6 \ libfontconfig1 \ python-software-properties \ libfreetype6 \ sudo \ tree \ figlet" sudo apt-get install -y less net-tools inetutils-ping curl git telnet nmap socat dnsutils netcat tree htop unzip sudo runit sudo apt-get install -y build-essential curl zlib1g-dev libreadline-dev libssl-dev libcurl4-openssl-dev git libmysqlclient-dev #Update your packages and install the ones that are needed to compile Ruby sudo apt-get install -y curl libxml2-dev libxslt-dev libcurl4-openssl-dev libreadline6-dev libssl-dev patch build-essential zlib1g-dev openssh-server libyaml-dev libicu-dev sudo apt-get install -y $list_apt <file_sep>/fix/permission.sh user_guest(){ sudo adduser guest --disabled-password --gecos "" } iser_docker(){ sudo useradd docker echo "docker:docker" | chpasswd sudo adduser docker sudo sudo mkdir -p /home/docker sudo chown -R docker:docker /home/docker } docker_user <file_sep>/bash/mkdir1.sh pass1(){ print_func local dir=/tmp/2 mkdir1 $dir ensure "test -d $dir" echo 1 > /tmp/1 cat1 /tmp/1 } fail1(){ bla bla } pass1 fail1 <file_sep>/.old/install/gitlab_ci_runner.sh https://github.com/pgolm/docker-gitlab-ci-runner/edit/master/Dockerfile # install gitlab-ci-runner WORKDIR /home/gitlab_ci_runner RUN git clone https://github.com/gitlabhq/gitlab-ci-runner.git runner # Jan 02, 2014 ENV RUNNER_REVISION 08f2260ae87e101f72194a27229b249d126e35fe RUN cd runner && git checkout $RUNNER_REVISION && . $HOME/.profile && bundle install # prepare SSH RUN mkdir -p $HOME/.ssh CMD cd $HOME/runner CMD . ../.profile && ssh-keyscan -H $GITLAB_SERVER_FQDN >> $HOME/.ssh/known_hosts && bundle exec ./bin/setup_and_run <file_sep>/circle.sh #!/usr/bin/env bash #/bin/bash -c 'RUN ps aux | grep mongo' #https://github.com/circleci?query=docker # -p 3000:3000 # docker run brownman/install_config_test env > /tmp/env.txt docker run brownman/install_config_test grunt-cli > /tmp/grunt.txt #sudo -u gitlab_ci_runner -H 'env' > /tmp/env.txt cp /tmp/env.txt $CIRCLE_ARTIFACTS/env.txt cp /tmp/grunt.txt $CIRCLE_ARTIFACTS/grunt.txt #docker run -d -e "SECRET_KEY_BASE=abcd1234" brownman/runner2 <<START #env #echo "SECRET_KEY_BASE: $SECRET_KEY_BASE" #START #cd /opt/mean1/myApp; #ls -l; #grunt test; #grunt; #sleep 10 #START #curl --retry 10 --retry-delay 5 -v http://localhost:3000 <file_sep>/fix/upstart.sh install(){ trace Fix upstart under a virtual host https://github.com/dotcloud/docker/issues/1024 sudo dpkg-divert --local --rename --add /sbin/initctl sudo rm -f /sbin/initctl sudo ln -s /bin/true /sbin/initctl } config(){ trace } test_install(){ trace } test_config(){ trace } commander $@ #echo "#!/bin/sh\nexit 0" | sudo too /usr/sbin/policy-rc.d <file_sep>/fix/user.sh install(){ # switch priveleges RUN adduser --disabled-login --gecos 'GitLab CI Runner' gitlab_ci_runner USER gitlab_ci_runner ENV HOME /home/gitlab_ci_runner } <file_sep>/.old/Dockerfile3 ## # Gitlab CI Runner with NodeJS MongoDB Redis # # This creates an image which contains an Gitlab CI Runner environment # for NodeJS app ecosystem # - Node.js 0.10.23 # - MongoDB 2.4.8 # - Redis 2.4.15 # - Git ## FROM truongsinh/nodejs-mongodb-redis MAINTAINER <NAME> <<EMAIL>> # Config ENV INSTALL_RUBY_VERSION 2.0.0-p247 ENV HOME /root WORKDIR /root # apt-get build deps, to be removed later RUN apt-get -y update \ && apt-get -y install build-essential wget unzip libssl-dev # This is neccesary at runtime. RUN apt-get -y install openssh-client git libicu-dev # install ruby, bundler, and clean up RUN wget http://cache.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p353.tar.gz \ && tar -xvzf ruby-2.0.0-p353.tar.gz \ && cd ruby-2.0.0-p353/ \ && ./configure --prefix=/usr/local --disable-install-rdoc \ && make && make install \ && cd .. \ && rm -rf ruby-2.0.0-p353* # install gitlab-ci-runner RUN wget --no-check-certificate https://github.com/gitlabhq/gitlab-ci-runner/archive/master.zip \ && unzip master.zip \ && rm -rf master.zip \ && cd gitlab-ci-runner-master \ && gem install bundler \ && bundle install # prepare SSH RUN mkdir -p /root/.ssh # Clean up RUN apt-get -y purge build-essential wget unzip libssl-dev \ && apt-get -y autoremove # Start MongoDB, Redis and Runner CMD mongod --fork -f /etc/mongodb.conf \ && redis-server /etc/redis/redis.conf \ && cd $HOME/gitlab-ci-runner-master && ssh-keyscan -H $GITLAB_SERVER_FQDN >> $HOME/.ssh/known_hosts && bundle exec ./bin/setup_and_run <file_sep>/install/mongo.sh #MongoDB #https://www.digitalocean.com/community/tutorials/how-to-install-a-mean-js-stack-on-an-ubuntu-14-04-server install(){ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list sudo apt-get update sudo apt-get install -y mongodb-org sudo mkdir -p /data/db sudo chown -R mongodb:mongodb /data } config(){ sudo mongod &>/dev/null & } test_install(){ trace } test_config(){ set +e while :;do commander sleep 1 ( sudo netstat -ntlp | grep mongo ) && break done return 0 } test_install(){ trace } commander $@ <file_sep>/proxy.sh #change user to root #RUN ./fix/permission.sh #make travis and docker passing step after step together #RUN ./travis.sh set -u echo "---------------------" echo "dir_start: $PWD" echo "---------------------" install1(){ sudo apt-get install -y pv toilet 1>/dev/null } where_am_i(){ echo $( cd `dirname $0`;echo $PWD; ) } set_env1(){ dir_self=$( where_am_i ) ln -s $dir_self/travis.sh /tmp } switch_user(){ sudo su -c 'whoami; echo $PATH' sudo su -c "/tmp/travis.sh $RUN" } steps(){ install1 set_env1 switch_user } steps
7f4c4dd7165eeeb25126f3b5f7454ed6921d48a1
[ "Markdown", "Dockerfile", "Shell" ]
24
Shell
brownman/install_config_test
70aa5d3d32ff137a1a460227c85bb74e3a08c82d
4a95466a0ebcd79eea35f33760a04d7d80838505
refs/heads/master
<repo_name>mzabriskie/rf-release<file_sep>/bin/release #!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)); var prompt = require('prompt'); var fs = require('fs'); var exec = require('child_process').exec; var color = require('cli-color'); var cyan = color.cyan; var yellow = color.yellow; var changelog = require('rf-changelog'); var pattern = /^[0-9]\.[0-9]+\.[0-9](-.+)?/; var version = argv.v || argv.version; var folder = argv.f || argv.folder; var schema = { properties: {} }; // If version wasn't supplied via argv, add it to prompt schema if (!version || !pattern.test(version)) { schema.properties.version = { description: 'version? (old is '+getCurrentVersion()+')', pattern: pattern, message: 'Must be a valid semver string i.e. 1.0.2, 2.3.0-beta.1', required: true }; } // If folder wasn't supplied via argv, add it to prompt schema if (!folder) { schema.properties.folder = { description: 'which folder should be published?', default: './' }; } // If version or folder are missing, run through prompt if (schema.properties.version || schema.properties.folder) { prompt.start(); prompt.get(schema, function(err, result) { release(result.version || version, result.folder || folder); }); } // Otherwise we have what's needed, just do it else { release(version, folder); } function release(version, folder) { updateJSON('package', version); updateJSON('bower', version); var tagVersion = 'v'+version; ex('npm test', function() { changelog('-t '+tagVersion, function() { commit(tagVersion, function() { tag(tagVersion, function() { publish(tagVersion, folder); }); }); }); }); } function commit(version, cb) { ex('git commit -am "release '+version+'"', cb); } function tag(version, cb) { ex('git tag '+version, function() { ex('git tag latest -f', cb); }); } function publish(version, folder) { ex('git push origin master', function() { ex('git push origin '+version, function() { ex('npm publish '+folder); }); }); } function ex(command, cb) { log(cyan('exec:'), yellow(command)); exec(command, execHandler(cb)); } function execHandler(cb) { return function(err, stdout, stderr) { if (err) throw new Error(err); console.log(stdout); console.log(stderr); if (cb) cb(); } } function updateJSON(pkg, version) { var path = pkg+'.json'; if (!fs.existsSync(path)) { return; } var json = readJSON(path); json.version = version; writeJSON(path, json); log(cyan('updated'), path); } function getCurrentVersion() { return readJSON('./package.json').version; } function readJSON(path) { return JSON.parse(fs.readFileSync(path).toString()); } function writeJSON(path, data) { fs.writeFileSync(path, JSON.stringify(data, null, 2)); } function log() { var args = [].slice.call(arguments, 0); console.log.apply(console, [cyan('release:')].concat(args)); }
5608e4dd32a2cbf5d75ad1404454afea184e934d
[ "JavaScript" ]
1
JavaScript
mzabriskie/rf-release
3586284a1b702ca61a49123ff57aacd9a6324833
4c1343c4a18531161568faebacac8af7d9762691
refs/heads/master
<repo_name>aivass/Combination-Lock<file_sep>/class.h #pragma once #include <iostream> #include <conio.h> #define KB_LEFT 75 //input values for left #define KB_RIGHT 77 //input values for right class lock { int num1; int num2; int num3; int current_number = 0; int state = 0; //lock state, 0 waiting for 1st correct, 1 waiting for 2nd correct...., 3 UNLOCKED int KB_code = 0; int last_direction = 0; // 1 left, 2 right int click_count = 0; public: void setnum1(int x) { num1 = x; } void setnum2(int x) { num2 = x; } void setnum3(int x) { num3 = x; } int getstate() { return state; } int getclick_count() { return click_count; } int getcurrent_number() { return current_number; } void keyboard_input(); void state_changer(); }; class keyboardinput { }; void lock::keyboard_input() { if (_kbhit()) //if a key has been pressed { KB_code = _getch(); //gets the keycode for left or right switch (KB_code) { case KB_LEFT: //if spin left if (lock::last_direction == 2) //if the spin direction has changed { lock::click_count = 0; //reset the click count } lock::current_number += 1; //incriment the current number if (lock::current_number == 40) //rollover 39 -> 0 lock::current_number = 0; lock::last_direction = 1; //remember the rotation direction lock::click_count += 1; //incriment the click count break; case KB_RIGHT: //if spin right if (lock::last_direction == 1) //if the spin direction has changed { lock::click_count = 0; //reset the click count } lock::current_number -= 1; //decriment the current number if (lock::current_number == -1) //rollover 0 -> 39 lock::current_number = 39; lock::last_direction = 2; //remember the rotation direction lock::click_count += 1; //incriment the click count break; } } } void lock::state_changer() { if (lock::state == 0 && lock::click_count > 40 && lock::last_direction == 1 && lock::current_number == lock::num1) //condition for first correct number, if true set state to start on second number state = 1; if (lock::state == 1 && lock::click_count > 40 && lock::last_direction == 2 && lock::current_number == lock::num2) //condition for second correct number, if true set state to start on third number state = 2; if (lock::state == 2 && lock::last_direction == 1 && lock::current_number == lock::num3) //condition for third correct number, if true the lock is unlocked state = 3; if (lock::state == 2 && lock::click_count > 40 && lock::current_number < lock::num2) //stops user from spin to win unlock state = 0; }
47a9dc9ca986d48b307150d49c405ea374ea0581
[ "C++" ]
1
C++
aivass/Combination-Lock
16d31c1ee4dcbc2b29d1f9f3677090b5d6e0ee4a
bcbf794318f0aef13d1fcbc3ddd8dff1b1c5de9d
refs/heads/master
<repo_name>aganne/AvisFormation.Web.UI<file_sep>/AvisController.cs using Avis.Data; using AvisFormation.Web.UI.Models; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AvisFormation.Web.UI.Controllers { public class AvisController : Controller { [Authorize] // GET: Avis public ActionResult LaisserUnAvis(string nomSeo) { if (!string.IsNullOrWhiteSpace(nomSeo)) { var avis = new LaissezUnAvisViewModel(nomSeo); if (avis.Formation != null) { return View(avis); } return RedirectToAction("Index", "Home"); } return RedirectToAction("Index", "Home"); } [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult SaveComment(AvisSave avis) { Avis.Data.Avis nouvelAvis = new Avis.Data.Avis(); nouvelAvis.IdFormation = avis.IdFormation; nouvelAvis.DateAvis = DateTime.Now; nouvelAvis.Description = avis.Description; nouvelAvis.Nom = User.Identity.GetUserName(); nouvelAvis.Note = avis.Note; nouvelAvis.UserId = User.Identity.GetUserId(); if (!EstAutoriseACommenter(nouvelAvis)) { TempData["Message"] = "Désolé, un seul avis par formation par compte utilisateur !"; return RedirectToAction("Error", "Erreur"); } using (var context = new AvisEntities()) { context.Avis.Add(nouvelAvis); context.SaveChanges(); } return RedirectToAction("Index", "Home", null); } private bool EstAutoriseACommenter(Avis.Data.Avis avisSave) { var avisManager = new LaissezUnAvisViewModel(); return avisManager.EstAutoriserAcommenter(avisSave); } // GET: Avis public ActionResult AfficherAvis() { AfficherAvisViewModels vm = new AfficherAvisViewModels(); return View(vm); } } }<file_sep>/DetailFormation.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avis.Data { public class DetailFormation : Formation { public DetailFormation() { } public DetailFormation(Formation formation) { base.Nom = formation.Nom; base.Id = formation.Id; base.Url = formation.Url; base.Description = formation.Description; base.NomSeo = formation.NomSeo; base.Avis = new List<Avis>(); } public double MoyenneDesVotes { get; set; } = 0; public int NombreVotant { get; set; } = 0; } } <file_sep>/AvisSave.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AvisFormation.Outils.Extension; namespace Avis.Data { public class AvisSave : Avis { public AvisSave() { } public AvisSave(string idFormation, string note) { _idFormationStr = idFormation; _noteStr = note; } public string NomSeo { get; set; } public string Commentaire { get; set; } private string _idFormationStr; private string _noteStr; public string IdFormationStr { get { return _idFormationStr; } set { int id = value.IntParseString(); if (id > 0) base.IdFormation = id; _idFormationStr = value; } } public string NoteStr { get { return _noteStr; } set { double id = value.DoubleParseString(); if (id > 0) base.Note = id; _noteStr = value; } } } } <file_sep>/LaissezUnAvisViewModel.cs using Avis.Data; using Avis.Logic; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AvisFormation.Web.UI.Models { public class LaissezUnAvisViewModel { public Formation Formation { get; set; } = null; public AvisManager AvisManager { get; set; } = new AvisManager(); public LaissezUnAvisViewModel() { } public LaissezUnAvisViewModel(string nomseo) { Formation formation = null; if (FormationManager.ObtenirFormation(nomseo, out formation)) this.Formation = formation; } public bool EstAutoriserAcommenter(Avis.Data.Avis avisSave) { using (var context=new AvisEntities()) { return !context.Avis.Any(avis => avis.IdFormation == avisSave.IdFormation && avis.UserId == avisSave.UserId); } } } }<file_sep>/FormationManager.cs using Avis.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avis.Logic { public class FormationManager { public List<Formation> ObtenirFormations() { List<Formation> ToutesFormations = null; using (var context = new AvisEntities()) { if (context.Formation.Any()) { ToutesFormations = new List<Formation>(); ToutesFormations = context.Formation.ToList(); } } return ToutesFormations; } /// <summary> /// Affichage de 4 formations au hazard sur la page d'accueil /// </summary> public List<DetailFormation> ObtenirDetailFormations() { var detailFormationListe = new List<DetailFormation>(); using (var context = new AvisEntities()) { List<Formation> formation = context.Formation.OrderBy(x => Guid.NewGuid()).Take(4).ToList(); foreach (Formation formationdetail in formation) { DetailFormation detailsFormations = ObtenirDetailsFormation(formationdetail.NomSeo); if (detailsFormations != null) detailFormationListe.Add(detailsFormations); } } return detailFormationListe; } public DetailFormation ObtenirDetailsFormation(string nomSeo) { DetailFormation detailFormationEntity = null; using (var context = new AvisEntities()) { Formation detailEntity = context.Formation.SingleOrDefault(f => f.NomSeo == nomSeo); if (detailEntity != null) { detailFormationEntity = new DetailFormation(detailEntity) { MoyenneDesVotes = 0, NombreVotant = 0 }; if (detailEntity.Avis.Any()) { detailFormationEntity.MoyenneDesVotes = Math.Round(detailEntity.Avis.Average(a => a.Note),1); detailFormationEntity.NombreVotant = detailEntity.Avis.Count(); detailFormationEntity.Avis = detailEntity.Avis.ToList(); } } } return detailFormationEntity; } public static bool ObtenirFormation(string nomSeo, out Formation formation) { formation = null; using (var context = new AvisEntities()) { var formationContext = context.Formation.SingleOrDefault(f => string.Compare(f.NomSeo, nomSeo, true) == 0); if (formationContext != null) { formation = formationContext; return true; } return false; } } } } <file_sep>/AvisManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Avis.Data; using Microsoft.SqlServer.Server; namespace Avis.Logic { public class AvisManager { public void AjouterAvis(Avis.Data.Avis avis) { using (var context = new AvisEntities()) { context.Avis.Add(avis); context.SaveChanges(); } } public List<Avis.Data.Avis> ObtenirAvis(int trainingId) { List<Avis.Data.Avis> TousAvis = null; using (var context = new AvisEntities()) { if (context.Avis.Any(a => a.IdFormation == trainingId)) { TousAvis = new List<Avis.Data.Avis>(); TousAvis = context.Avis.Where(a => a.IdFormation == trainingId).ToList(); } } return TousAvis; } public List<DetailAvis> ObtenirTousLesAvis() { List<DetailAvis> derniersAvisListe = null; using (var context = new AvisEntities()) { if (context.Avis.Any()) { derniersAvisListe = new List<DetailAvis>(); var derniersAvis = context.Avis.OrderByDescending(a=>a.DateAvis).Take(10).ToList(); if (derniersAvis!=null) { foreach (Avis.Data.Avis item in derniersAvis) { DetailAvis da = new DetailAvis(item.DateAvis); da.Formation = new Formation(); da.Formation.Nom = item.Formation.Nom; da.Description = item.Description; da.Nom = item.Nom; derniersAvisListe.Add(da); } } } } return derniersAvisListe; } } } <file_sep>/README.md # AvisFormation.Web.UI Presentation du code MVC Projet en ligne sur https://coach.aganne.com/ Hébergement sur Ikoula <file_sep>/DetailAvis.cs using AvisFormation.Outils.Extension; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Avis.Data { public class DetailAvis : Avis { public string TempsDepuisPublication { get; set; } public DetailAvis(DateTime value) { TempsDepuisPublication = value.JourDepuisCetteDate(); } } }
e5ffc3dd7b054e03964ef9946368875e7a9a67f0
[ "Markdown", "C#" ]
8
C#
aganne/AvisFormation.Web.UI
29f8f56093ca156a89b5452b101eafe71aa3b1f7
2cc6eb017da5d793aec78dfe7dd9dade3c09774a
refs/heads/master
<repo_name>mossti/regforms<file_sep>/Registration/Managers/LoadStudentDetails.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Registration.Models; using System.Web.Mvc; using System.Data.Entity; namespace Registration.Managers { // Name: LoadStudentDetails // Pupose: Generic class that breaks up the selection of data required for each of the different views. Some bits are common to all the views. Others are specific to each of the views. Originally // created this to use tabs to display, then changed so that each view was standalone. Some impact on performance but ensured that the tick/cross for each one was handled seperately. Number of users // deemed insignificant in terms of numbers hitting the site at once as there are only a couple of thousand users, and very few at the same time. // Autor: <NAME> // Version: 1.0 // Date: 07/03/2016 // Update: // Version 1.1 // Date: 22/04/2016 // Details: Amendment of system - removing medical approval consent and drug treatment consent on Medical view. Medical approval added to Accommodation view for under 18 year olds. public class LoadStudentDetails { public static void LoadIntroModel(IntroductionModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.email = app.email; aem.mobile_tel = app.mobile_tel; aem.unspent_conviction_details = app.unspent_conviction_details; aem.unspent_convictions = app.unspent_convictions; /* Create 5 blank records in the relevant table if there aren't any for that student */ LoadStudentDetails.AddMedicalRecords(id); } } } public static void LoadConModel(ConsentsModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.photography_consent = app.photography_consent; aem.work_placement_consent = app.work_placement_consent; } } } public static void LoadMedModel(MedicalModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.gp_postcode = app.gp_postcode; aem.gp_practice = app.gp_practice; aem.gp_telephone = app.gp_telephone; aem.immunisation_acknowledgement = app.immunisation_acknowledgement; aem.medical_disability_issue = app.medical_disability_issue; aem.social_emotional_mental_health = app.social_emotional_mental_health; aem.medical_treatment_consent_details = app.medical_treatment_consent_details; //aem.over_counter_medical_treatment = app.over_counter_medical_treatment; aem.SocialEmotionalMentalHealthDetails = app.SocialEmotionalMentalHealthDetails; aem.MedicalIssues = _db.medical_issues.Where(a => a.app_id == id).OrderBy(a => a.id).ToList(); } } } public static void LoadSupportArrangementsModel(SupportArrangementsModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.learning_difficulty_disability = app.learning_difficulty_disability; aem.cognitive_learning = app.cognitive_learning; aem.communication_sensory = app.communication_sensory; aem.physical_sensory = app.physical_sensory; aem.learning_difficulty_disability_details = app.learning_difficulty_disability_details; aem.s139a_transition_statement = app.s139a_transition_statement; aem.ed_psych_ldd_assessment = app.ed_psych_ldd_assessment; aem.care_leaver_in_care = app.care_leaver_in_care; aem.support_worker_email = app.support_worker_email; aem.support_worker_name = app.support_worker_name; aem.support_worker_tel = app.support_worker_tel; aem.young_parent_young_carer = app.young_parent_young_carer; aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == id && a.FileType == "S").ToList(); } } } public static void LoadPhotoModel(PhotoModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == id && a.FileType == "P").ToList(); } } } public static void LoadTransportModel(TransportModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.transport_web_payment_receipt_number = app.transport_web_payment_receipt_number; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.transport_id = app.transport_id; aem.transport_type_id = app.transport_type_id; aem.stagecoach_home_station = app.stagecoach_home_station; LoadTransportLists(aem, _currentyear); } } } public static void LoadTransportLists(TransportModel aem, string _currentyear) { int _wheelerstravel = 0; int _campustaxi = 0; int _wiltsanddorset = 0; int _stagecoachmegarider = 0; int _southwesttrains = 0; int _campusbus = 0; int _trainandno7 = 0; int _stagecoachgolderider = 0; int _hegoldrider = 0; int _stagecoachno7 = 0; using (var _db = new AppsEntities()) { var _transporttypes = _db.transport_type.AsNoTracking().Where(a => a.acad_period == _currentyear && a.campus == aem.campus && a.isactive == true).Select(x => new { x.student_type, x.transport_type_desc, x.transport_type_id }).OrderBy(a => a.transport_type_id).ToList(); aem.AvailableTransportTypes.Add(new SelectListItem { Text = "Please select one", Value = "" }); foreach (var _t in _transporttypes) { if (_t.student_type == 1) { aem.AvailableTransportTypes.Add(new SelectListItem() { Text = _t.transport_type_desc, Value = _t.transport_type_id.ToString() }); } // Get the variables as we are looping to load the selectlist if (_t.transport_type_desc == "Wheelers Travel") { _wheelerstravel = _t.transport_type_id; } if (_t.transport_type_desc == "Campus Taxi") { _campustaxi = _t.transport_type_id; } if (_t.transport_type_desc == "AC Campus Bus") { _wiltsanddorset = _t.transport_type_id; } if (_t.transport_type_desc == "Stagecoach Megarider") { _stagecoachmegarider = _t.transport_type_id; } if (_t.transport_type_desc == "South West Trains") { _southwesttrains = _t.transport_type_id; } if (_t.transport_type_desc == "No.7 Pass") { _stagecoachno7 = _t.transport_type_id; } if (_t.transport_type_desc == "HE Goldrider Pass") { _hegoldrider = _t.transport_type_id; } if (_t.transport_type_desc == "Stagecoach Goldrider") { _stagecoachgolderider = _t.transport_type_id; } if (_t.transport_type_desc == "Combined Rail and No.7 bus pass") { _trainandno7 = _t.transport_type_id; } if (_t.transport_type_desc == "Campus Bus") { _campusbus = _t.transport_type_id; } }; if (!string.IsNullOrEmpty(aem.transport_type_id.ToString())) { var _transportselection = _db.transports.AsNoTracking().Where(a => a.acad_period == _currentyear && a.campus == aem.campus && a.transport_type_id == aem.transport_type_id).Select(x => new { x.transport_type_id, x.transport_id, x.boarding_point }).OrderBy(x => x.boarding_point).ToList(); aem.AvailableTransportItems.Add(new SelectListItem { Text = "Please select one", Value = "" }); foreach (var _t in _transportselection) { if (_t.transport_type_id != _hegoldrider) { aem.AvailableTransportItems.Add(new SelectListItem() { Text = _t.boarding_point, Value = _t.transport_id.ToString() }); } } } // Read all transport costs in to memory and then filter rather than hit the database 10 times List<transport_costs> _alltransportcosts = _db.transport_costs.AsNoTracking().Where(a => a.acad_period == _currentyear).ToList(); aem.campusbuscosts = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _campusbus).ToList(); aem.combinedrailandno7costs = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _trainandno7).ToList(); aem.StageCoachGoldRiderCost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _stagecoachgolderider).Select(a => a.cost).FirstOrDefault(); aem.HEGoldRiderCost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _hegoldrider).Select(a => a.cost).FirstOrDefault(); aem.StageCoachNo7Cost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _stagecoachno7).Select(a => a.cost).FirstOrDefault(); aem.StageCoachMegariderCost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _stagecoachmegarider).Select(a => a.cost).FirstOrDefault(); aem.CampusTaxiCost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _campustaxi).Select(a => a.cost).FirstOrDefault(); aem.WheelersTravelCost = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _wheelerstravel).Select(a => a.cost).FirstOrDefault(); aem.southwestrainscosts = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _southwesttrains).Select(a => a.cost).FirstOrDefault(); aem.wiltsanddorsetcosts = _alltransportcosts.Where(a => a.campus == aem.campus && a.transport_type_id == _wiltsanddorset).Select(a => a.cost).FirstOrDefault(); } } public static void LoadAccommodationModel(AccommodationModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; aem.medical_treatment_consent = app.medical_treatment_consent; aem.he_goldrider = app.he_goldrider.Value; aem.first_choice_accommodation_id = app.first_choice_accommodation_id; aem.second_choice_accommodation_id = app.second_choice_accommodation_id; aem.third_choice_accommodation_id = app.third_choice_accommodation_id; aem.accommodation_web_payment_receipt_number = app.accommodation_web_payment_receipt_number; aem.any_other_questions = app.any_other_questions; aem.transfer_deposit = app.transfer_deposit; LoadAccommodationLists(aem, _currentyear); } } } public static void LoadAccommodationLists(AccommodationModel aem, string _currentyear) { using (var _db = new AppsEntities()) { aem.HEGoldRiderCost = _db.transport_type.Join(_db.transport_costs, tt => new { tt.acad_period, tt.campus, tt.transport_type_id }, tc => new { tc.acad_period, tc.campus, tc.transport_type_id }, (tt, tc) => new { tt, tc }) .Where(o => o.tt.acad_period == _currentyear && o.tt.transport_type_desc == "HE Goldrider Pass" && o.tt.campus == aem.campus && o.tt.isactive == true) .Select(o => o.tc.cost).First(); aem.accommodationcosts = _db.accommodations.AsNoTracking().Where(a => a.acad_period == _currentyear && a.age_group == aem.age_group && a.student_type == aem.student_type && a.VetNurse == aem.VetNurse).ToList(); aem.AvailableAccommodationTypes.Add(new SelectListItem { Text = "Please select one", Value = "" }); var _accommodations = _db.accommodations.AsNoTracking().Where(a => a.acad_period == _currentyear && a.age_group == aem.age_group && a.student_type == aem.student_type && a.VetNurse == aem.VetNurse).OrderBy(a => a.accommodation_id).ToList(); foreach (var _t in _accommodations) { aem.AvailableAccommodationTypes.Add(new SelectListItem() { Text = _t.accommodation_description, Value = _t.accommodation_id.ToString() }); }; } } public static void LoadFinancialSupportModel(FinancialSupportModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; } } } public static void LoadSummaryModel(MinimalEntryModel aem, int id) { using (var _db = new AppsEntities()) { string _currentyear = _db.academicyears.AsNoTracking().Where(a => a.is_current == true).Select(a => a.acad_period).FirstOrDefault(); var app = _db.applicants.Where(a => a.app_id == id && a.acad_period == _currentyear).First(); if (app != null) { aem.acad_period = app.acad_period; aem.app_id = app.app_id; aem.campus = app.campus; aem.forenames = app.forenames; aem.student_id = app.student_id; aem.student_type = app.student_type; aem.surname = app.surname; aem.age_on_entry = app.age_on_entry.Value; aem.current_age = LoadStudentDetails.GetAge(app.dob.Value); aem.wants_accommodation = app.wants_accommodation; aem.wants_transport = app.wants_transport; aem.IntroComplete = app.IntroComplete; aem.ConsentsComplete = app.ConsentsComplete; aem.MedicalComplete = app.MedicalComplete; aem.SupportArrangementsComplete = app.SupportArrangementsComplete; aem.TransportComplete = app.TransportComplete; aem.AccommodationComplete = app.AccommodationComplete; aem.FinancialSupportComplete = app.FinancialSupportComplete; aem.Submitted = app.Submitted; aem.dob = app.dob.Value; aem.PhotoComplete = app.PhotoComplete; aem.VetNurse = app.VetNurse.Value; } } } private static void AddMedicalRecords(int _appid) { using (var _db = new AppsEntities()) { var medcount = _db.medical_issues.Where(m => m.app_id == _appid).Count(); if (medcount < 5) { var _medicalIssues = _db.medical_issues.Create(); /* Create 5 new records */ for (int i = 0; i < 5; i++) { _medicalIssues.app_id = _appid; _medicalIssues.rowid = i; _db.medical_issues.Add(_medicalIssues); _db.SaveChanges(); } } } return; } public static int GetAge(DateTime birthDate) { int age = DateTime.Now.Year - birthDate.Year; if (birthDate.DayOfYear > DateTime.Now.DayOfYear) age--; return age; } } }<file_sep>/Registration/ViewModels/MedicalModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class MedicalModel : MinimalEntryModel { public Nullable<bool> medical_disability_issue { get; set; } public string gp_practice { get; set; } [Column(TypeName = "varchar")] public string gp_postcode { get; set; } [Column(TypeName = "varchar")] public string gp_telephone { get; set; } public bool immunisation_acknowledgement { get; set; } public Nullable<bool> social_emotional_mental_health { get; set; } public List<medical_issues> MedicalIssues { get; set; } public string medical_treatment_consent_details { get; set; } //public Nullable<bool> over_counter_medical_treatment { get; set; } public string SocialEmotionalMentalHealthDetails { get; set; } } }<file_sep>/Registration/ViewModels/UserLoginModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class UserLoginModel { [Required(ErrorMessage = "Please enter your student id number provided in the email. It is 11 characters long and is made up of 3 character and 8 numbers.", AllowEmptyStrings = false)] [Display(Name = "Student Id:")] [StringLength(11, MinimumLength = 11)] [Column(TypeName = "varchar")] public string student_id { get; set; } [Required(ErrorMessage = "Please enter your password. It should be between 6 and 20 characters.", AllowEmptyStrings = false)] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6)] [Display(Name = "Password:")] [Column(TypeName = "varchar")] public string password { get; set; } } }<file_sep>/Registration/ViewModels/IntroductionModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class IntroductionModel : MinimalEntryModel { [EmailAddress] [StringLength(100)] [Display(Name = "Email Address:")] [Required(ErrorMessage = "Email address required")] [Column(TypeName = "varchar")] public string email { get; set; } [Required(ErrorMessage = "Mobile number required")] [StringLength(15)] [Column(TypeName = "varchar")] public string mobile_tel { get; set; } public Nullable<bool> unspent_convictions { get; set; } [Column(TypeName = "varchar")] public string unspent_conviction_details { get; set; } } }<file_sep>/Registration/ViewModels/MinimalEntryModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class MinimalEntryModel { public int app_id { get; set; } [Column(TypeName = "varchar")] public string student_id { get; set; } [Column(TypeName = "varchar")] public string acad_period { get; set; } public int student_type { get; set; } [Column(TypeName = "varchar")] public string campus { get; set; } public string surname { get; set; } [Column(TypeName = "varchar")] public string forenames { get; set; } public DateTime dob { get; set; } public string campus_logo { get { return this.campus == "ANDO" ? "~/Images/andover.jpg" : "~/Images/sparsholt.jpg"; } } public int age_on_entry { get; set; } [Column(TypeName = "varchar")] public int age_group { get { return this.age_on_entry < 18 ? 1 : 2; } } public int current_age { get; set; } public bool wants_transport { get; set; } public bool wants_accommodation { get; set; } public bool Submitted { get; set; } public bool IntroComplete { get; set; } public bool ConsentsComplete { get; set; } public bool MedicalComplete { get; set; } public bool SupportArrangementsComplete { get; set; } public bool TransportComplete { get; set; } public bool AccommodationComplete { get; set; } public bool FinancialSupportComplete { get; set; } public bool PhotoComplete { get; set; } public bool VetNurse { get; set; } } }<file_sep>/Registration/Controllers/ErrorController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Registration.Controllers { // Name: ErrorController // Pupose: Handles general erros by opening specifc error views. // Autor: <NAME> // Version: 1.0 // Date: 13/01/2016 public class ErrorController : Controller { public ActionResult Error404() { return View("404"); } public ActionResult Error500() { return View("500"); } public ActionResult Error403() { HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden; return View("403"); } } }<file_sep>/Registration/ViewModels/PasswordResetRequestViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class PasswordResetRequestViewModel { [Required(ErrorMessage = "Please enter your student id number provided in the email. It is 11 characters long and is made up of 3 character and 8 numbers.", AllowEmptyStrings = false)] [Display(Name = "Student Id:")] [StringLength(11, MinimumLength = 11)] [Column(TypeName = "varchar")] public string student_id { get; set; } } }<file_sep>/Registration/Controllers/HomeController.cs using Registration.Models; using System; using System.Net; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using AutoMapper; using System.Web.Security; using Registration.Managers; using System.Net.Mail; using System.IO; using System.Web.Configuration; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; namespace Registration.Controllers { // Name: HomeController // Pupose: Main controller for the system. Includes HttpGet and HttpPost action results for views used to capture data for each person logged in to system. Basic data is get from MIS system by database stored procedure. // GetTransportList is used to create drop down list of transport details based on change of existing data. // Use of "Save and Next" on each view ensures that the controller captures any errors and then ensures that the next view is shown depending on the Wants Transport/Wants Accommodation checkboxes etc. // Autor: <NAME> // Version: 1.0 // Date: 09/03/2016 // Update: // Version 1.1 // Date: 22/04/2016 // Details: // GetPhoto allows existing photo of applicant to be added to the database. // SupportArrangements allows multiple existing files (Word, PDF etc) to be stored in database. public class HomeController : Controller { private bool IsValidLogin(string studentId, string username) { if (studentId.ToUpper() == username.ToUpper()) { using (var _db = new AppsEntities()) { var user = _db.user_login.FirstOrDefault(a => a.student_id == studentId); if (user != null) { return true; } else { return false; } } } else { return false; } } [HttpGet] [AllowAnonymous] public ActionResult Contact() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Contact(ContactUsModel cum) { string message = cum.Message + string.Format(" from {0} at {1}", cum.YourName, cum.Email); string emailadminaccount = WebConfigurationManager.AppSettings["EmailAdminAccount"].ToString(); if (!EmailClass.SendEmail(emailadminaccount, cum.Subject, message)) { return View(); } else { return RedirectToAction("Contact"); } } [HttpGet] [AllowAnonymous] public ActionResult LoggedOut() { return View(); } [HttpGet] public JsonResult UpdateWantsTransport(bool newValue, int id) { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(id); acc.wants_transport = newValue; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); return Json(true, JsonRequestBehavior.AllowGet); } } [HttpGet] public JsonResult UpdateWantsAccommodation(bool newValue, int id) { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(id); acc.wants_accommodation = newValue; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); return Json(true, JsonRequestBehavior.AllowGet); } } [HttpGet] public JsonResult GetTransportList(int id, string campus, string aperiod) { using (var _db = new AppsEntities()) { var _transportdetails = (from s in _db.transports join tt in _db.transport_type on s.transport_type_id equals tt.transport_type_id where s.transport_type_id == id && s.acad_period == aperiod && s.campus == campus && tt.student_type == 1 && tt.isactive == true select new { id = s.transport_id, name = s.boarding_point }).ToList(); return Json(_transportdetails, JsonRequestBehavior.AllowGet); } } [HttpGet] public ActionResult Introduction() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); IntroductionModel aem = new IntroductionModel(); LoadStudentDetails.LoadIntroModel(aem, id); return View("Introduction", aem); } [HttpGet] public ActionResult Consents() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); ConsentsModel aem = new ConsentsModel(); LoadStudentDetails.LoadConModel(aem, id); return View("Consents", aem); } [HttpGet] public ActionResult Medical() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); MedicalModel aem = new MedicalModel(); LoadStudentDetails.LoadMedModel(aem, id); return View("Medical", aem); } [HttpGet] public ActionResult SupportArrangements() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); SupportArrangementsModel aem = new SupportArrangementsModel(); LoadStudentDetails.LoadSupportArrangementsModel(aem, id); return View("SupportArrangements", aem); } [HttpGet] public ActionResult Photo() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); PhotoModel aem = new PhotoModel(); LoadStudentDetails.LoadPhotoModel(aem, id); return View("Photo", aem); } [HttpGet] public ActionResult Transport() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); TransportModel aem = new TransportModel(); LoadStudentDetails.LoadTransportModel(aem, id); return View("Transport", aem); } [HttpGet] public ActionResult Accommodation() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); AccommodationModel aem = new AccommodationModel(); LoadStudentDetails.LoadAccommodationModel(aem, id); return View("Accommodation", aem); } [HttpGet] public ActionResult FinancialSupport() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); FinancialSupportModel aem = new FinancialSupportModel(); LoadStudentDetails.LoadFinancialSupportModel(aem, id); return View("FinancialSupport", aem); } [HttpGet] public ActionResult Summary() { int id = Int32.Parse(FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name); MinimalEntryModel aem = new MinimalEntryModel(); LoadStudentDetails.LoadSummaryModel(aem, id); return View("Summary", aem); } [HttpGet] public ActionResult GetPhoto(int id) { using (var _db = new AppsEntities()) { // Find the relevant record file_uploads ptp = _db.file_uploads.Find(id); if (ptp == null) { return File(UrlHelper.GenerateContentUrl("~/Images/unknownuser.jpg", HttpContext), "image/jpeg"); } else { byte[] imageData = ptp.UploadedFileData; if (imageData != null && imageData.Length > 0) { string contentType = MimeMapping.GetMimeMapping(ptp.UploadedFileName); return new FileStreamResult(new System.IO.MemoryStream(imageData), contentType); } else { return File(UrlHelper.GenerateContentUrl("~/Images/unknownuser.jpg", HttpContext), "image/jpeg"); } } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Introduction(IntroductionModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Introduction", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); //string email = _db.user_login.AsNoTracking().Where(a => a.student_id == acc.student_id).Select(a => a.email).FirstOrDefault(); if (acc != null) { //if (!email.ToLower().Equals(aem.email.ToLower())) //{ // ModelState.AddModelError("email", "The email you registered with and the one on the form are different."); // //ViewBag.StudentEmail = _db.user_login.AsNoTracking().Where(a => a.student_id == studentId).Select(a => a.email).FirstOrDefault(); // return View("Introduction", aem); //} if (!aem.unspent_convictions.HasValue) { ModelState.AddModelError("unspent_convictions", "Please indicate whether or not you have unspent convictions."); return View("Introduction", aem); } string _studentid = acc.student_id; string _currentyear = acc.acad_period; acc.mobile_tel = aem.mobile_tel; acc.email = aem.email; acc.wants_accommodation = aem.wants_accommodation; acc.wants_transport = aem.wants_transport; acc.unspent_convictions = aem.unspent_convictions; acc.unspent_conviction_details = aem.unspent_conviction_details; acc.IntroComplete = true; if (acc.student_type == 2 || acc.student_type == 3) { acc.FinancialSupportComplete = true; } _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } if (aem.current_age < 18) { return RedirectToAction("Consents"); } else { return RedirectToAction("Photo"); } } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Consents(ConsentsModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Consents", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { if (aem.current_age < 18) { if (!aem.work_placement_consent.HasValue) { ModelState.AddModelError("work_placement_consent", "Please select Yes or No for work placement consent."); return View("Consents", aem); } if (!aem.photography_consent.HasValue) { ModelState.AddModelError("photography_consent", "Please select Yes or No for photography consent."); return View("Consents", aem); } } else { aem.work_placement_consent = true; aem.photography_consent = true; } //Mapper.CreateMap<applicant, ApplicantToEditModel>(); acc.work_placement_consent = aem.work_placement_consent; acc.photography_consent = aem.photography_consent; acc.ConsentsComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } // Can now go to the next page return RedirectToAction("Photo"); } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Photo(PhotoModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Photo", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { /* Upload any files that may be attached */ file_uploads fileUploadModel = new file_uploads(); if (aem.File != null) { byte[] uploadFile = null; byte[] uploadThumbNailFile = null; using (var binaryReader = new BinaryReader(aem.File.InputStream)) { uploadFile = binaryReader.ReadBytes(aem.File.ContentLength); } /* Create two scaled versions of the original image - one is a thumbnail - convert the byte array to an image and then use the image.getthumbnailimage to create the thumbnail */ System.Drawing.Image newImage; //Read image data into a memory stream using (MemoryStream ms = new MemoryStream(uploadFile, 0, uploadFile.Length)) { ms.Write(uploadFile, 0, uploadFile.Length); //Set image variable value using memory stream. newImage = System.Drawing.Image.FromStream(ms, true); } Bitmap myBitmap = new Bitmap(new Bitmap(newImage)); System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(PhotoHelper.ThumbnailCallback); /* Scale the original image to minimize database record size */ System.Drawing.Image myFullSize = myBitmap.GetThumbnailImage(320, 240, myCallback, IntPtr.Zero); /* Thumbnail image size matches what is on ProS */ System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(128, 96, myCallback, IntPtr.Zero); /* Need to convert the newly created images back to byte arrays in order to save them */ uploadFile = PhotoHelper.imageToByteArray(myFullSize); uploadThumbNailFile = PhotoHelper.imageToByteArray(myThumbnail); fileUploadModel.UploadedFileName = aem.File.FileName; fileUploadModel.UploadedFileData = uploadFile; fileUploadModel.ThumbNailUploadedFileData = uploadThumbNailFile; fileUploadModel.app_id = aem.app_id; fileUploadModel.FileType = "P"; _db.file_uploads.Add(fileUploadModel); } acc.PhotoComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } return RedirectToAction("Medical"); } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Medical(MedicalModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Medical", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { //if (!aem.medical_treatment_consent.HasValue) //{ // ModelState.AddModelError("medical_treatment_consent", "Please select whether or not you consent to receiving medical treatment in an emergency."); // return View("Medical", aem); //} //if (!aem.over_counter_medical_treatment.HasValue) //{ // ModelState.AddModelError("over_counter_medical_treatment", "Please indicate whether or not you agree to receiving over the counter drugs if necessary."); // return View("Medical", aem); //} if (!aem.medical_disability_issue.HasValue) { ModelState.AddModelError("medical_disability_issue", "Please indicate whether or not you have a medical or disability issue."); return View("Medical", aem); } if (!aem.social_emotional_mental_health.HasValue) { ModelState.AddModelError("social_emotional_mental_health", "Please indicate whether or not you have a social, emotional or mental health issue."); return View("Medical", aem); } if (!aem.immunisation_acknowledgement) { ModelState.AddModelError("immunisation_acknowledgement", "Please indicate that you have read the information regarding immunisation."); return View("Medical", aem); } //if ((aem.medical_treatment_consent == false) && (aem.medical_treatment_consent_details == null)) //{ // ModelState.AddModelError("medical_treatment_consent_details", "Please give details regarding the types of potentially life saving treatment you are refusing."); // return View("Medical", aem); //} //acc.medical_treatment_consent = aem.medical_treatment_consent; acc.medical_disability_issue = aem.medical_disability_issue; acc.social_emotional_mental_health = aem.social_emotional_mental_health; acc.medical_treatment_consent_details = aem.medical_treatment_consent_details; //acc.over_counter_medical_treatment = aem.over_counter_medical_treatment; acc.SocialEmotionalMentalHealthDetails = aem.SocialEmotionalMentalHealthDetails; acc.gp_practice = aem.gp_practice; acc.gp_postcode = aem.gp_postcode; acc.gp_telephone = aem.gp_telephone; acc.immunisation_acknowledgement = aem.immunisation_acknowledgement; // Need to update the existing medical issue records int i = 0; foreach (var md in _db.medical_issues.Where(a => a.app_id == aem.app_id).OrderBy(a => a.rowid)) { md.issue_description = aem.MedicalIssues[i].issue_description; md.issue_prescription = aem.MedicalIssues[i].issue_prescription; _db.Entry(md).State = EntityState.Modified; i++; } acc.MedicalComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } return RedirectToAction("SupportArrangements"); } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult SupportArrangements(SupportArrangementsModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("SupportArrangements", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { //if (!aem.care_leaver_in_care.HasValue) //{ // ModelState.AddModelError("care_leaver_in_care", "Please select whether or not you are in care or a care leaver."); // return View("SupportArrangements", aem); //} //if (!aem.young_parent_young_carer.HasValue) //{ // ModelState.AddModelError("young_parent_young_carer", "Please select whether or not you are a young parent or young carer."); // return View("SupportArrangements", aem); //} if (aem.learning_difficulty_disability == null) { ModelState.AddModelError("learning_difficulty_disability", "Please indicate whether or not you have a learning difficulty or disability."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } if (aem.learning_difficulty_disability == true) { if (!aem.cognitive_learning.HasValue) { ModelState.AddModelError("cognitive_learning", "Please indicate whether or not you have a cognitive learning issue."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } if (!aem.communication_sensory.HasValue) { ModelState.AddModelError("communication_sensory", "Please indicate whether or not you have a communication or sensory learning issue."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } if (!aem.physical_sensory.HasValue) { ModelState.AddModelError("physical_sensory", "Please indicate whether or not you have a physical or sensory learning issue."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } if (!aem.s139a_transition_statement.HasValue) { ModelState.AddModelError("s139a_transition_statement", "Please indicate whether or not you have a S139a Transitional Statement."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } if (!aem.ed_psych_ldd_assessment.HasValue) { ModelState.AddModelError("ed_psych_ldd_assessment", "Please indicate whether or not you have an Education Pyschologist's LDD Assessment ."); aem.LoadedFiles = _db.file_uploads.Where(a => a.app_id == aem.app_id && a.FileType == "S").ToList(); return View("SupportArrangements", aem); } } else { aem.cognitive_learning = false; aem.communication_sensory = false; aem.physical_sensory = false; aem.s139a_transition_statement = false; aem.ed_psych_ldd_assessment = false; } acc.learning_difficulty_disability = aem.learning_difficulty_disability; acc.learning_difficulty_disability_details = aem.learning_difficulty_disability_details; acc.cognitive_learning = aem.cognitive_learning; acc.communication_sensory = aem.communication_sensory; acc.physical_sensory = aem.physical_sensory; acc.s139a_transition_statement = aem.s139a_transition_statement; acc.ed_psych_ldd_assessment = aem.ed_psych_ldd_assessment; acc.care_leaver_in_care = aem.care_leaver_in_care; acc.support_worker_name = aem.support_worker_name; acc.support_worker_tel = aem.support_worker_tel; acc.support_worker_email = aem.support_worker_email; acc.young_parent_young_carer = aem.young_parent_young_carer; acc.SupportArrangementsComplete = true; _db.Entry(acc).State = EntityState.Modified; /* Upload any files that may be attached - BinaryReader deals with image and text type files */ file_uploads fileUploadModel1 = new file_uploads(); foreach (var item in aem.File1) { if (item != null) { byte[] uploadFile = null; using (var binaryReader = new BinaryReader(item.InputStream)) { uploadFile = binaryReader.ReadBytes(item.ContentLength); fileUploadModel1.UploadedFileName = item.FileName; fileUploadModel1.UploadedFileData = uploadFile; } fileUploadModel1.app_id = aem.app_id; fileUploadModel1.FileType = "S"; _db.file_uploads.Add(fileUploadModel1); } } file_uploads fileUploadModel2 = new file_uploads(); foreach (var item in aem.File2) { if (item != null) { byte[] uploadFile = null; using (var binaryReader = new BinaryReader(item.InputStream)) { uploadFile = binaryReader.ReadBytes(item.ContentLength); fileUploadModel2.UploadedFileName = item.FileName; fileUploadModel2.UploadedFileData = uploadFile; } fileUploadModel2.app_id = aem.app_id; fileUploadModel2.FileType = "S"; _db.file_uploads.Add(fileUploadModel2); } } _db.SaveChanges(); } if (acc.wants_transport == true) { return RedirectToAction("Transport"); } else if ((acc.wants_transport == false) && (acc.wants_accommodation == true)) { return RedirectToAction("Accommodation"); } else { if (acc.student_type == 1) { return RedirectToAction("FinancialSupport"); } else { return RedirectToAction("Summary"); } } } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Transport(TransportModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Transport", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { if (aem.transport_web_payment_receipt_number == null) { ModelState.AddModelError("transport_web_payment_receipt_number", "Please record the order number generated by the payment system."); LoadStudentDetails.LoadTransportLists(aem, acc.acad_period); return View("Transport", aem); } if (aem.transport_web_payment_receipt_number.Substring(0, 2).ToUpper() != "OS") { ModelState.AddModelError("transport_web_payment_receipt_number", "Please record the order number generated by the payment system."); LoadStudentDetails.LoadTransportLists(aem, acc.acad_period); return View("Transport", aem); } acc.wants_transport = true; acc.stagecoach_home_station = aem.stagecoach_home_station; acc.transport_type_id = aem.transport_type_id; acc.transport_id = aem.transport_id; acc.transport_web_payment_receipt_number = aem.transport_web_payment_receipt_number; acc.TransportComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } if (acc.wants_accommodation == true) { return RedirectToAction("Accommodation"); } else { if (acc.student_type == 1) { return RedirectToAction("FinancialSupport"); } else { return RedirectToAction("Summary"); } } } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Accommodation(AccommodationModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Accommodation", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc != null) { if (!aem.transfer_deposit) { if (aem.accommodation_web_payment_receipt_number == null) { ModelState.AddModelError("accommodation_web_payment_receipt_number", "Please record the order number generated by the payment system."); LoadStudentDetails.LoadAccommodationLists(aem, acc.acad_period); return View("Accommodation", aem); } if (aem.accommodation_web_payment_receipt_number.Substring(0, 2).ToUpper() != "OS") { ModelState.AddModelError("accommodation_web_payment_receipt_number", "Please record the order number generated by the payment system."); LoadStudentDetails.LoadAccommodationLists(aem, acc.acad_period); return View("Accommodation", aem); } } acc.wants_accommodation = true; acc.first_choice_accommodation_id = aem.first_choice_accommodation_id; acc.second_choice_accommodation_id = aem.second_choice_accommodation_id; // If HE then leave blank unless a Vet Nurse if (aem.student_type == 2 && aem.VetNurse == true) { acc.third_choice_accommodation_id = aem.third_choice_accommodation_id; } else { acc.third_choice_accommodation_id = null; } acc.accommodation_web_payment_receipt_number = aem.accommodation_web_payment_receipt_number; acc.transfer_deposit = aem.transfer_deposit; acc.any_other_questions = aem.any_other_questions; // HE applicant does not see this on drop down of transports but might have picked it on accommodation page if (aem.he_goldrider == true && aem.student_type == 2) { int _hestagecoachtypeid = (from a1 in _db.transport_type where a1.transport_type_desc == "HE Goldrider Pass" && a1.acad_period == aem.acad_period select a1.transport_type_id).Single(); int _hestagecoachid = (from a1 in _db.transports where a1.transport_type_id == _hestagecoachtypeid && a1.acad_period == aem.acad_period select a1.transport_id).Single(); acc.transport_type_id = _hestagecoachtypeid; acc.transport_id = _hestagecoachid; acc.he_goldrider = aem.he_goldrider; } acc.medical_treatment_consent = aem.medical_treatment_consent; acc.AccommodationComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } if (acc.student_type == 1) { return RedirectToAction("FinancialSupport"); } else { return RedirectToAction("Summary"); } } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult FinancialSupport(FinancialSupportModel aem, string command) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("FinancialSupport", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); string email = _db.user_login.AsNoTracking().Where(a => a.student_id == acc.student_id).Select(a => a.email).FirstOrDefault(); if (acc != null) { acc.FinancialSupportComplete = true; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } return RedirectToAction("Summary"); } } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Summary(MinimalEntryModel aem) { if (!ModelState.IsValid) { //LoadStudentDetails.GetModel(apped); ModelState.AddModelError("", "There are errors in the data."); return View("Summary", aem); } else { using (var _db = new AppsEntities()) { var acc = _db.applicants.Find(aem.app_id); if (acc.IntroComplete == false) { return RedirectToAction("Introduction"); } if ((acc.age_on_entry < 18) && (acc.ConsentsComplete == false)) { return RedirectToAction("Consents"); } if (acc.MedicalComplete == false) { return RedirectToAction("Medical"); } if (acc.SupportArrangementsComplete == false) { return RedirectToAction("SupportArrangements"); } if ((acc.wants_transport == true) && (acc.TransportComplete == false)) { return RedirectToAction("Transport"); } if ((acc.wants_accommodation == true) && (acc.AccommodationComplete == false)) { return RedirectToAction("Accommodation"); } if (aem.Submitted == true && acc.Submitted == false) { acc.SubmittedDate = DateTime.Now.ToShortDateString(); } acc.Submitted = aem.Submitted; if (aem.Submitted == true) { if (acc.completion_email_sent == false) { TempData["AlertMessage"] = "Your registration form has been submitted."; string subject = "Confirmation email"; string messagebody = "Thank you for using the on-line registration system. We confirm receipt of your registration form. If we require any clarification then we will contact you soon, otherwise we will be in contact with you again before you come to College to enrol."; if (EmailClass.SendEmail(acc.email, subject, messagebody)) { acc.completion_email_sent = true; acc.completion_email_sent_date = DateTime.Now; } else { acc.completion_email_sent = false; } } } else { TempData["AlertMessage"] = "Your registration form has not yet been submitted. When you are ready to do so, please tick the Form Submission check box and then press Save."; } _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); return RedirectToAction("Summary"); } } } [HttpGet] public ActionResult FileDelete(int id, string FileType) { using (var _db = new AppsEntities()) { // Find the relevant record file_uploads ptp = _db.file_uploads.Find(id); _db.file_uploads.Remove(ptp); _db.SaveChanges(); if (FileType == "S") { return RedirectToAction("SupportArrangements"); } else { return RedirectToAction("Photo"); } } } [HttpGet] public ActionResult FileDownload(int id) { using (var _db = new AppsEntities()) { // Find the relevant record file_uploads ptp = _db.file_uploads.Find(id); string contentType = MimeMapping.GetMimeMapping(ptp.UploadedFileName); var cd = new System.Net.Mime.ContentDisposition { FileName = ptp.UploadedFileName, // always prompt the user for downloading, set to true if you want // the browser to try to show the file inline Inline = false, }; Response.AppendHeader("Content-Disposition", cd.ToString()); return File(ptp.UploadedFileData, contentType); } } } } <file_sep>/Registration/Managers/EmailClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Registration.Models; using System.Web.Mvc; using System.Net; using System.Net.Mail; namespace Registration.Managers { // Name: EmailClass // Pupose: Creates emails to be sent to someone registering on the system. The email server details are in the web.config files. // Autor: <NAME> // Version: 1.0 // Date: 11/01/2016 public class EmailClass { public static Boolean SendEmail(string email, string subject, string messagebody) { using (MailMessage message = new MailMessage()) { message.To.Add(new MailAddress(email)); message.From = new MailAddress("<EMAIL>"); message.Subject = subject; message.Body = messagebody; message.IsBodyHtml = true; using (SmtpClient smtp = new SmtpClient()) { try { smtp.Send(message); return true; } catch (Exception ex) { Console.WriteLine("Exception caught in send mail: {0}", ex.ToString()); return false; } } } } } }<file_sep>/Registration/ViewModels/PhotoModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class PhotoModel : MinimalEntryModel { [System.ComponentModel.DisplayName("File Upload")] public HttpPostedFileBase File { get; set; } public List<file_uploads> LoadedFiles { get; set; } } }<file_sep>/Registration/ViewModels/ApplicantToEditModelOrig.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class ApplicantToEditModelOrig { public Nullable<System.DateTime> updated_date { get; set; } [EmailAddress] [StringLength(100)] [Display(Name = "Email Address:")] [Required(ErrorMessage = "Email address required")] [Column(TypeName = "varchar")] public string email { get; set; } [Column(TypeName = "varchar")] public string mobile_tel { get; set; } public Nullable<bool> unspent_convictions { get; set; } [Column(TypeName = "varchar")] public string unspent_conviction_details { get; set; } [Required(ErrorMessage = "Medical treatment consent required")] [Display(Name = "Medical Treatment Consent")] public Nullable<bool> medical_treatment_consent { get; set; } [Required(ErrorMessage = "Work placement consent required")] public Nullable<bool> work_placement_consent { get; set; } public bool photography_consent { get; set; } public Nullable<int> care_leaver_in_care { get; set; } [Column(TypeName = "varchar")] public string support_worker_name { get; set; } [Column(TypeName = "varchar")] public string support_worker_tel { get; set; } [Column(TypeName = "varchar")] public string support_worker_email { get; set; } public Nullable<int> young_parent_young_carer { get; set; } [Required] public bool applicant_confirmation { get; set; } public bool parent_guardian_confirmation { get; set; } public Nullable<System.DateTime> parent_guardian_confirmation_date { get; set; } [Column(TypeName = "varchar")] public string gp_practice { get; set; } [Column(TypeName = "varchar")] public string gp_postcode { get; set; } [Column(TypeName = "varchar")] public string gp_telephone { get; set; } public bool immunisation_acknowledgement { get; set; } public bool learning_difficulty_disability { get; set; } public bool cognitive_learning { get; set; } public bool social_emotional_mental_health { get; set; } public bool communication_sensory { get; set; } public bool physical_sensory { get; set; } [Column(TypeName = "varchar")] public string learning_difficulty_disability_details { get; set; } public bool s139a_transition_statement { get; set; } public bool ed_psych_ldd_assessment { get; set; } public Nullable<int> first_choice_accommodation_id { get; set; } public Nullable<int> second_choice_accommodation_id { get; set; } public Nullable<int> third_choice_accommodation_id { get; set; } public bool manual_payment { get; set; } public bool transfer_deposit { get; set; } [Column(TypeName = "varchar")] public string any_other_questions { get; set; } public Nullable<int> studentdetailid { get; set; } public Nullable<int> transport_id { get; set; } public Nullable<int> transport_type_id { get; set; } [Column(TypeName = "varchar")] public string web_payment_receipt_number { get; set; } [Column(TypeName = "varchar")] public string parent_guardian_name { get; set; } public bool medical_disability_issue { get; set; } public bool wants_residential_bursary_info { get; set; } public bool wants_travel_bursary_info { get; set; } public IEnumerable<SelectListItem> campusbus { get; set; } public List<transport_costs> campusbuscosts { get; set; } public IEnumerable<SelectListItem> combinedrailandno7 { get; set; } public List<transport_costs> combinedrailandno7costs { get; set; } public IEnumerable<SelectListItem> transporttypes { get; set; } public IEnumerable<SelectListItem> transports { get; set; } public double StageCoachGoldRiderCost { get; set; } public double HEGoldRiderCost { get; set; } public double StageCoachNo7Cost { get; set; } public double StageCoachMegariderCost { get; set; } public double CampusTaxiCost { get; set; } public double WheelersTravelCost { get; set; } public double southwestrainscosts { get; set; } public double wiltsanddorsetcosts { get; set; } public bool stagecoach_home_station { get; set; } public bool Submitted { get; set; } public bool he_goldrider { get; set; } public ApplicantToEditModelOrig() { AvailableTransportTypes = new List<SelectListItem>(); AvailableTransportItems = new List<SelectListItem>(); AvailableAccommodationTypes = new List<SelectListItem>(); } public List<SelectListItem> AvailableTransportTypes { get; set; } public List<SelectListItem> AvailableTransportItems { get; set; } public List<SelectListItem> AvailableAccommodationTypes { get; set; } public List<medical_issues> MedicalIssues { get; set; } public List<accommodation> accommodationcosts { get; set; } } }<file_sep>/Registration/ViewModels/SupportArrangementsModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class SupportArrangementsModel : MinimalEntryModel { public Nullable<bool> learning_difficulty_disability { get; set; } public Nullable<bool> cognitive_learning { get; set; } public Nullable<bool> communication_sensory { get; set; } public Nullable<bool> physical_sensory { get; set; } [Column(TypeName = "varchar")] public string learning_difficulty_disability_details { get; set; } public Nullable<bool> s139a_transition_statement { get; set; } public Nullable<bool> ed_psych_ldd_assessment { get; set; } public int care_leaver_in_care { get; set; } [Column(TypeName = "varchar")] public string support_worker_name { get; set; } [Column(TypeName = "varchar")] public string support_worker_tel { get; set; } [Column(TypeName = "varchar")] public string support_worker_email { get; set; } public int young_parent_young_carer { get; set; } [System.ComponentModel.DisplayName("File Upload")] public IEnumerable<HttpPostedFileBase> File1 { get; set; } public IEnumerable<HttpPostedFileBase> File2 { get; set; } public List<file_uploads> LoadedFiles { get; set; } } }<file_sep>/Registration/Managers/PhotoHelper.cs  using System.Collections.Generic; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Mvc.Html; using System.Drawing; namespace Registration.Managers { public static class PhotoHelper { public static bool ThumbnailCallback() { return false; } public static byte[] imageToByteArray(System.Drawing.Image image) { using (var ms = new MemoryStream()) { image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); return ms.ToArray(); } } } }<file_sep>/Registration/Scripts/inputtoupper.js function InputToUpper(obj) { if (obj.value != "") { obj.value = obj.value.toUpperCase(); } } <file_sep>/Registration/ViewModels/FinancialSupportModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class FinancialSupportModel : MinimalEntryModel { public bool wants_residential_bursary_info { get; set; } public bool wants_travel_bursary_info { get; set; } } }<file_sep>/Registration/ViewModels/ConsentsModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class ConsentsModel : MinimalEntryModel { [Required(ErrorMessage = "Work placement consent required")] public Nullable<bool> work_placement_consent { get; set; } public Nullable<bool> photography_consent { get; set; } } }<file_sep>/Registration/App_Start/MappingConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using Registration.Models; namespace Registration.App_Start { public static class MappingConfig { public static void RegisterMaps() { AutoMapper.Mapper.Initialize(config => { //config.CreateMap<applicant, ApplicantToEditModel>() // .ForMember(dest => dest.campusbus, opt => opt.Ignore()) // .ForMember(dest => dest.campusbuscosts, opt => opt.Ignore()) // .ForMember(dest => dest.combinedrailandno7, opt => opt.Ignore()) // .ForMember(dest => dest.combinedrailandno7costs, opt => opt.Ignore()) // .ForMember(dest => dest.transporttypes, opt => opt.Ignore()) // .ForMember(dest => dest.transports, opt => opt.Ignore()) // .ForMember(dest => dest.StageCoachGoldRiderCost, opt => opt.Ignore()) // .ForMember(dest => dest.HEGoldRiderCost, opt => opt.Ignore()) // .ForMember(dest => dest.StageCoachNo7Cost, opt => opt.Ignore()) // .ForMember(dest => dest.StageCoachMegariderCost, opt => opt.Ignore()) // .ForMember(dest => dest.CampusTaxiCost, opt => opt.Ignore()) // .ForMember(dest => dest.WheelersTravelCost, opt => opt.Ignore()) // .ForMember(dest => dest.southwestrainscosts, opt => opt.Ignore()) // .ForMember(dest => dest.wiltsanddorsetcosts, opt => opt.Ignore()) // .ForMember(dest => dest.AvailableTransportTypes, opt => opt.Ignore()) // .ForMember(dest => dest.AvailableTransportItems, opt => opt.Ignore()) // .ForMember(dest => dest.AvailableAccommodationTypes, opt => opt.Ignore()) // .ForMember(dest => dest.MedicalIssues, opt => opt.Ignore()) // .ForMember(dest => dest.accommodationcosts, opt => opt.Ignore()); config.CreateMap<user_login, UserViewModel>() .ForMember(dest => dest.confirm_password, opt => opt.Ignore()) .ForMember(dest => dest.Day, opt => opt.Ignore()) .ForMember(dest => dest.Month, opt => opt.Ignore()) .ForMember(dest => dest.Year, opt => opt.Ignore()); //config.CreateMap<applicant, MinimalEntryModel>(); }); } } }<file_sep>/Registration/ViewModels/AccommodationModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class AccommodationModel : MinimalEntryModel { public Nullable<int> first_choice_accommodation_id { get; set; } public Nullable<int> second_choice_accommodation_id { get; set; } public Nullable<int> third_choice_accommodation_id { get; set; } public bool transfer_deposit { get; set; } [Column(TypeName = "varchar")] public string any_other_questions { get; set; } [RegularExpression(@"[a-zA-Z]{2}\d{5}", ErrorMessage = "Please enter a valid receipt number.")] public string accommodation_web_payment_receipt_number { get; set; } [Column(TypeName = "varchar")] public bool he_goldrider { get; set; } public double HEGoldRiderCost { get; set; } public AccommodationModel() { AvailableAccommodationTypes = new List<SelectListItem>(); } public Nullable<bool> medical_treatment_consent { get; set; } public List<SelectListItem> AvailableAccommodationTypes { get; set; } public List<accommodation> accommodationcosts { get; set; } } }<file_sep>/Registration/App_Start/RouteConfig.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Registration { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //routes.MapRoute( // name: "RegistrationConfirmation", // url: "{controller}/{action}/{eKey}", // defaults: new { controller = "User", action = "ConfirmRegistration" } //); //routes.MapRoute( // name: "PasswordChangeConfirmation", // url: "{controller}/{action}/{eKey}", // defaults: new { controller = "User", action = "ConfirmPasswordResetRequest" } //); routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "User", action = "Registration" } ); routes.MapRoute( name: "GetTransportList", url: "Home/GetTransportList/", defaults: new { controller = "Home", action = "GetTransportList" } ); routes.MapRoute( name: "UpdateWantsTransport", url: "Home/UpdateWantsTransport/", defaults: new { controller = "Home", action = "UpdateWantsTransport" } ); routes.MapRoute( name: "UpdateWantsAccommodation", url: "Home/UpdateWantsAccommodation/", defaults: new { controller = "Home", action = "UpdateWantsAccommodation" } ); routes.MapRoute("404-PageNotFound", "{*url}", new { controller = "Error", action = "Error404" }); } } } <file_sep>/Registration/ViewModels/UserPasswordChangeModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class UserPasswordChangeModel { public string student_id { get; set; } public string guid { get; set; } [Required(ErrorMessage = "Please enter your password. It should be between 6 and 20 characters.", AllowEmptyStrings = false)] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6)] [Display(Name = "Password:")] [Column(TypeName = "varchar")] public string password { get; set; } [Required(ErrorMessage = "Please enter your password again.", AllowEmptyStrings = false)] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6)] [Display(Name = "Confirm Password:")] [Column(TypeName = "varchar")] public string confirm_password { get; set; } } }<file_sep>/Registration/ViewModels/UserViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class UserViewModel { [Required(ErrorMessage = "Please enter your student id number provided in the email. It is 11 characters long and is made up of 3 character and 8 numbers.", AllowEmptyStrings = false)] [Display(Name = "Student Id:")] [StringLength(11, MinimumLength = 11)] [Column(TypeName = "varchar")] public string student_id { get; set; } [Required(ErrorMessage = "Please enter your password. It should be between 6 and 20 characters.", AllowEmptyStrings = false)] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6)] [Display(Name = "Password:")] [Column(TypeName = "varchar")] public string password { get; set; } [Required(ErrorMessage = "Please enter your password again.", AllowEmptyStrings = false)] [DataType(DataType.Password)] [StringLength(20, MinimumLength = 6)] [Display(Name = "Confirm Password:")] [Column(TypeName = "varchar")] [Compare("password", ErrorMessage = "The password and confirmation do not match.")] public string confirm_password { get; set; } [EmailAddress(ErrorMessage = "Invalid Email Address")] [Required(ErrorMessage = "Please enter your email address.", AllowEmptyStrings = false)] [DataType(DataType.EmailAddress)] [Display(Name = "Email Address:")] public string email { get; set; } [Required(ErrorMessage = "Please enter your day of birth.", AllowEmptyStrings = false)] public int Day { get; set; } [Required(ErrorMessage = "Please enter your month of birth.", AllowEmptyStrings = false)] public int Month { get; set; } [Required(ErrorMessage = "Please enter your year of birth.", AllowEmptyStrings = false)] public int Year { get; set; } } }<file_sep>/Registration/Controllers/UserController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Registration.Models; using System.Web.Security; using Registration.Managers; using System.IO; using System.Data.Entity; using System.Text; using System.Web.Configuration; // Name: UserController // Pupose: Manages registration of new logins and login of users to the system. Also has functionality to deal with password resets. // Once a user registers (using the student id that we send them), the account is created and an emails sent to the user asking them to confirm that they have registered. Clicking on the link opens a new // window and auto logs in the user. // The majority of controller actions are filtered to ensure only authorised users are able to access them. // Passwords are encrypted and salted using a custom crypto class that uses MD5 and TripleDesc encryption. // Autor: <NAME> // Version: 1.0 // Date: 09/03/2016 // Update: // Version 1.1 // Date: 11/04/2016 // Details: Changed so that rather than store the student id in the cookie, store the application id corresponding to the student id. Saves on one extra database trip and will always use the clustered index namespace Registration.Controllers { public class UserController : Controller { // // GET: /User/ [HttpGet] [AllowAnonymous] public ActionResult Welcome() { FormsAuthentication.SignOut(); return View(); } [HttpGet] [AllowAnonymous] public ActionResult Login() { // Force any existing cookie to be removed FormsAuthentication.SignOut(); return View(); } [HttpGet] [AllowAnonymous] public ActionResult NotFound() { // Force any existing cookie to be removed FormsAuthentication.SignOut(); return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(UserLoginModel user) { if (ModelState.IsValid) { if (IsValid(user.student_id, user.password)) { using (var _db = new AppsEntities()) { string appid = _db.applicants.AsNoTracking().Where(a => a.student_id == user.student_id).Select(a => a.app_id).FirstOrDefault().ToString(); // Using the "old" style forms authentication cookie because the new (VS2013) ASP.NET authorisation system is based on email addresses and I want to use the student id as the registration key // The cookie is encrypted automatically using MachineKey. if (appid == null) { string emailadminaccount = WebConfigurationManager.AppSettings["EmailAdminAccount"].ToString(); EmailClass.SendEmail(emailadminaccount, "Error in identifying record", string.Format("Unable to locate the application record for {0}", user.student_id)); return RedirectToAction("NotFound", "User"); } else { FormsAuthentication.SetAuthCookie(appid, false); return RedirectToAction("Introduction", "Home"); } } } else { ModelState.AddModelError("", "Login data is incorrect - please check your password"); return View("Login", user); } } else { ModelState.AddModelError("", "Login data is incorrect - please check your password"); return View("Login", user); } } [HttpGet] [AllowAnonymous] public ActionResult Registration() { FormsAuthentication.SignOut(); return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Registration(UserViewModel user) { if (!ModelState.IsValid) { ModelState.AddModelError("", "There are errors on the page"); return View("Registration", user); } else { using (var db = new AppsEntities()) { DateTime _dob = new DateTime(user.Year, user.Month, user.Day); string _studentid = user.student_id; // Need to check that the student has not already registered var _noduplicate = db.user_login.FirstOrDefault(a => a.student_id == _studentid); if (_noduplicate == null) { // Need to check to see if the student id and date of birth correspond to a valid student - if not, then reload model and return to view, else procede with account registration var _validStudent = db.applicants.Where(a => a.student_id == _studentid && a.dob == _dob).Select(a => a.student_id).FirstOrDefault(); if (_validStudent != null) { if (user.password == user.confirm_password) { var crypto = new SimpleCrypto.PBKDF2(); var encryptPassword = crypto.Compute(user.password); var sysUser = db.user_login.Create(); sysUser.student_id = _studentid; sysUser.email = user.email; sysUser.password = <PASSWORD>; sysUser.password_salt = crypto.Salt; sysUser.created_date = DateTime.Now; sysUser.student_guid = Base64ForUrlEncode(Guid.NewGuid().ToString()); sysUser.email_sent = false; db.user_login.Add(sysUser); db.SaveChanges(); if (SendRegistrationEmail(_studentid)) { return RedirectToAction("Login", "User"); } } else { ModelState.AddModelError("", "Passwords do not match"); } } else { ModelState.AddModelError("", "Invalid combination of studentid and birth date"); } } else { ModelState.AddModelError("", "This student id has already been registered. Please use the login screen."); } } } return View("Registration", user); } [HttpGet] public ActionResult LogOut() { FormsAuthentication.SignOut(); return RedirectToAction("LoggedOut", "Home"); } private bool IsValid(string UserName, string Password) { var crypto = new SimpleCrypto.PBKDF2(); bool isValid = false; using (var _db = new AppsEntities()) { var user = _db.user_login.FirstOrDefault(a => a.student_id == UserName); if (user != null) { if (user.password == crypto.Compute(Password, user.password_salt)) { isValid = true; } } } return isValid; } private bool SendRegistrationEmail(string _studentId) { Boolean outcome = true; using (var _db = new AppsEntities()) { var user = _db.user_login.FirstOrDefault(a => a.student_id == _studentId); if (user != null) { //string subject = "Please confirm your account registration"; //string messagebody = "Please click on the following link to confirm your registration: https://regforms.sparsholt.ac.uk/User/ConfirmRegistration?grt=" + user.student_guid + "&sen=" + Base64ForUrlEncode(user.student_id); string subject = "Confirmation of account registration"; string messagebody = "You have successfully registered with the on-line registration system."; if (EmailClass.SendEmail(user.email, subject, messagebody)) { user.email_sent = true; } else { user.email_sent = false; outcome = false; } _db.Entry(user).State = EntityState.Modified; _db.SaveChanges(); return outcome; } else { return outcome; } } } [HttpGet] [AllowAnonymous] public ActionResult ConfirmRegistration(string grt, string sen) { using (var _db = new AppsEntities()) { var _studentId = Base64ForUrlDecode(sen); var user = _db.user_login.FirstOrDefault(a => a.student_id == _studentId && a.student_guid == grt); if (user != null) { // Make sure that the email used in registration is the same as the one on the application var acc = _db.applicants.Where(a => a.student_id == _studentId).FirstOrDefault(); if (acc.email != user.email) { acc.email = user.email; _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } string appid = acc.app_id.ToString(); FormsAuthentication.SetAuthCookie(appid, false); return RedirectToAction("Introduction", "Home"); } else { string emailadminaccount = WebConfigurationManager.AppSettings["EmailAdminAccount"].ToString(); EmailClass.SendEmail(emailadminaccount, "Error in registration", string.Format("An error occurred in the confirmation registration of {0}", _studentId)); return RedirectToAction("InvalidRegistration"); } } } [HttpGet] [AllowAnonymous] public ActionResult InvalidRegistration() { return View(); } [HttpGet] [AllowAnonymous] public ActionResult PasswordResetRequest() { return View(); } [HttpPost] [AllowAnonymous] public ActionResult PasswordResetRequest(PasswordResetRequestViewModel prrv) { using (var _db = new AppsEntities()) { var user = _db.user_login.FirstOrDefault(a => a.student_id == prrv.student_id); if (user != null) { string messagebody = "Please click on the following link to change your password: https://regforms.sparsholt.ac.uk/User/ConfirmPasswordResetRequest?grt=" + user.student_guid + "&sen=" + Base64ForUrlEncode(user.student_id); EmailClass.SendEmail(user.email, "Password Change Request", messagebody); ViewBag.SuccessMessage = "An email is on its way to you now. You can close this window."; } else { return RedirectToAction("PasswordResetRequest"); } } return View(); } [HttpGet] [AllowAnonymous] public ActionResult ConfirmPasswordResetRequest(string grt, string sen) { using (var _db = new AppsEntities()) { var _studentId = Base64ForUrlDecode(sen); var user = _db.user_login.FirstOrDefault(a => a.student_id == _studentId && a.student_guid == grt); if (user != null) { return RedirectToAction("PasswordReset", new { g = grt, s = sen }); } else { string emailadminaccount = WebConfigurationManager.AppSettings["EmailAdminAccount"].ToString(); EmailClass.SendEmail(emailadminaccount, "Error in registration", string.Format("An error occurred in the confirmation registration of {0}", _studentId)); return RedirectToAction("PasswordResetRequest"); } } } [HttpGet] [AllowAnonymous] public ActionResult PasswordReset(string g, string s) { UserPasswordChangeModel upcm = new UserPasswordChangeModel(); upcm.student_id = Base64ForUrlDecode(s); upcm.guid = g; return View(upcm); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult PasswordReset(UserPasswordChangeModel upcm) { if (ModelState.IsValid) { using (var _db = new AppsEntities()) { var acc = _db.user_login.FirstOrDefault(a => a.student_id == upcm.student_id && a.student_guid == upcm.guid); if (acc != null) { if (upcm.password == upcm.confirm_password) { var crypto = new SimpleCrypto.PBKDF2(); var encryptPassword = crypto.Compute(upcm.password); acc.password = <PASSWORD>; acc.password_salt = <PASSWORD>; acc.created_date = DateTime.Now; acc.student_guid = Base64ForUrlEncode(Guid.NewGuid().ToString()); _db.Entry(acc).State = EntityState.Modified; _db.SaveChanges(); } else { ModelState.AddModelError("Error", "Passwords do not match"); return View(upcm); } } else { ModelState.AddModelError("Error", "Invalid student id identified"); return View(upcm); } } } return RedirectToAction("Login"); } ///<summary> /// Base 64 Encoding with URL and Filename Safe Alphabet using UTF-8 character set. ///</summary> ///<param name="str">The origianl string</param> ///<returns>The Base64 encoded string</returns> public static string Base64ForUrlEncode(string str) { byte[] encbuff = Encoding.UTF8.GetBytes(str); return HttpServerUtility.UrlTokenEncode(encbuff); } ///<summary> /// Decode Base64 encoded string with URL and Filename Safe Alphabet using UTF-8. ///</summary> ///<param name="str">Base64 code</param> ///<returns>The decoded string.</returns> public static string Base64ForUrlDecode(string str) { byte[] decbuff = HttpServerUtility.UrlTokenDecode(str); return Encoding.UTF8.GetString(decbuff); } } }<file_sep>/Registration/Scripts/Registration.js  // check for default status (when checked, show the transport block) if (($('input#wants_transport[type=checkbox]').attr('checked') !== undefined) || ($('input#wants_transport').val() == "True")) { $('#Transport_li').show(); } else { $('#Transport_li').hide(); } // check for default status (when checked, show the accommodation block) if (($('input#wants_accommodation[type=checkbox]').attr('checked') !== undefined && document.getElementById("hdnCampus").value == "SPAR") || ($('input#wants_accommodation').val() == "True" && document.getElementById("hdnCampus").value == "SPAR")) { $('#Accommodation_li').show(); } else { $('#Accommodation_li').hide(); } $("#first_choice_accommodation_id").change(function () { var accommodationchosen1 = $('#first_choice_accommodation_id').val(); $("#second_choice_accommodation_id option[value='" + accommodationchosen1 + "']").remove(); $("#third_choice_accommodation_id option[value='" + accommodationchosen1 + "']").remove(); }); $("#second_choice_accommodation_id").change(function () { var accommodationchosen1 = $('#first_choice_accommodation_id').val(); var accommodationchosen2 = $('#second_choice_accommodation_id').val(); $("#third_choice_accommodation_id option[value='" + accommodationchosen1 + "']").remove(); $("#third_choice_accommodation_id option[value='" + accommodationchosen2 + "']").remove(); }); $("#UnspentConvictions").hide(); var radioValue = $("input[name='unspent_convictions']:checked").val(); if (radioValue == "True") { $("#UnspentConvictions").show(); } else { $("#UnspentConvictions").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'unspent_convictions') { var radioValue = $("input[name='unspent_convictions']:checked").val(); if (radioValue == "True") { $("#UnspentConvictions").show(); } else { $("#UnspentConvictions").hide(); } }; }); $("#SupportWorker").hide(); $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'care_leaver_in_care') { var radioValue = $("input[name='care_leaver_in_care']:checked").val(); if (radioValue != 0) { $("#SupportWorker").show(); } else { $("#SupportWorker").hide(); } }; }); var radioValue = $("input[name='care_leaver_in_care']:checked").val(); if (radioValue != 0) { $("#SupportWorker").show(); } else { $("#SupportWorker").hide(); } $("#LearningIssueDetails").hide(); var radioValue = $("input[name='learning_difficulty_disability']:checked").val(); if (radioValue == "True") { $("#LearningIssueDetails").show(); } else { $("#LearningIssueDetails").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'learning_difficulty_disability') { var radioValue = $("input[name='learning_difficulty_disability']:checked").val(); if (radioValue == "True") { $("#LearningIssueDetails").show(); } else { $("#LearningIssueDetails").hide(); } }; }); $("#fileupload1").hide(); var radioValue = $("input[name='s139a_transition_statement']:checked").val(); if (radioValue == "True") { $("#fileupload1").show(); } else { $("#fileupload1").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 's139a_transition_statement') { var radioValue = $("input[name='s139a_transition_statement']:checked").val(); if (radioValue == "True") { $("#fileupload1").show(); } else { $("#fileupload1").hide(); } }; }); $("#fileupload2").hide(); var radioValue = $("input[name='ed_psych_ldd_assessment']:checked").val(); if (radioValue == "True") { $("#fileupload2").show(); } else { $("#fileupload2").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'ed_psych_ldd_assessment') { var radioValue = $("input[name='ed_psych_ldd_assessment']:checked").val(); if (radioValue == "True") { $("#fileupload2").show(); } else { $("#fileupload2").hide(); } }; }); $("#MedicalIssueDetails").hide(); var radioValue = $("input[name='medical_disability_issue']:checked").val(); if (radioValue == "True") { $("#MedicalIssueDetails").show(); } else { $("#MedicalIssueDetails").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'medical_disability_issue') { var radioValue = $("input[name='medical_disability_issue']:checked").val(); if (radioValue == "True") { $("#MedicalIssueDetails").show(); } else { $("#MedicalIssueDetails").hide(); } }; }); $("#SocialEmotionalMentalHealthDetailsSection").hide(); var radioValue = $("input[name='social_emotional_mental_health']:checked").val(); if (radioValue == "True") { $("#SocialEmotionalMentalHealthDetailsSection").show(); } else { $("#SocialEmotionalMentalHealthDetailsSection").hide(); } $('input[type="radio"]').click(function () { if ($(this).attr('id') == 'social_emotional_mental_health') { var radioValue = $("input[name='social_emotional_mental_health']:checked").val(); if (radioValue == "True") { $("#SocialEmotionalMentalHealthDetailsSection").show(); } else { $("#SocialEmotionalMentalHealthDetailsSection").hide(); } }; }); <file_sep>/Registration/ViewModels/TransportModel.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations.Schema; namespace Registration.Models { public class TransportModel : MinimalEntryModel { public Nullable<int> transport_id { get; set; } public Nullable<int> transport_type_id { get; set; } [Column(TypeName = "varchar")] public IEnumerable<SelectListItem> campusbus { get; set; } public List<transport_costs> campusbuscosts { get; set; } public IEnumerable<SelectListItem> combinedrailandno7 { get; set; } public List<transport_costs> combinedrailandno7costs { get; set; } [RegularExpression(@"[a-zA-Z]{2}\d{5}", ErrorMessage = "Please enter a valid receipt number.")] public string transport_web_payment_receipt_number { get; set; } public IEnumerable<SelectListItem> transporttypes { get; set; } public IEnumerable<SelectListItem> transports { get; set; } public double StageCoachGoldRiderCost { get; set; } public double HEGoldRiderCost { get; set; } public double StageCoachNo7Cost { get; set; } public double StageCoachMegariderCost { get; set; } public double CampusTaxiCost { get; set; } public double WheelersTravelCost { get; set; } public double southwestrainscosts { get; set; } public double wiltsanddorsetcosts { get; set; } public bool stagecoach_home_station { get; set; } public TransportModel() { AvailableTransportTypes = new List<SelectListItem>(); AvailableTransportItems = new List<SelectListItem>(); } public List<SelectListItem> AvailableTransportTypes { get; set; } public List<SelectListItem> AvailableTransportItems { get; set; } } }
e2e04f10e006f8ec5450bdbd8955ac536df7f8d4
[ "JavaScript", "C#" ]
24
C#
mossti/regforms
9a8d9b8b42fa47c24dbb0ee9b04c3aef5ed0dbcf
30f6ee8d0a0e28a0d167db87bd1dc2969f7b356a
refs/heads/master
<file_sep><?php class Product_filter_model extends CI_Model { public function __construct(){ parent::__construct(); $this->load->model('product_filter_model'); } public function fetch_filter_type() { // $this->load->database(); $this->db->distinct(); $this->db->select('product.group_name'); $query=$this->db->get('product'); return $query->result_array(); } } ?> <file_sep><?php foreach ($results as $product): ?> <br><br><br><br> <div class="carousel-inner"> <div class="item carousel-item active"> <div class="row"> <div class="col-sm-3"> <div class="thumb-wrapper"> <div class="img-box"> <img src="<?php echo $product['image_usr']; ?>" class="float-left"><br> </div> <div class="thumb-content"> <b><br> <a href="<?php echo site_url('/product/'.$product['lc_style']); ?>"><?php echo $product['brand_description']; ?></a>s <br><?php echo $product['display_name_en']; ?> <br><br> <?php if($product['available_channel']=="Online"): ?> <button class="button button1">online</button> <button2 class="button button2">In-store</button2> <?php elseif($product['available_channel']=='Both'): ?> <button class="button button1">online</button> <button1 class="button button1" >In-store</button1> <?php elseif($product['available_channel']=='offline'): ?> <button class="button button1" >online</button> <button2 class="button button2" >In-store</button2> <?php endif; ?> </b> </div> </div> </div> </div> </div> </div> <?php endforeach; ?><file_sep><!-- <?php foreach ($groupe as $g) {print_r($g); echo $g['group_name'];} ?> --> <html> <title> product filter </title> <link rel="stylesheet" href="https://bootswatch.com/3/flatly/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <body> <div class="container"> <div class="row"> <div class="col-md-3"> <br /> <br /> <br /> <div class="list-group"> <h3>Filter By Department</h3> <?php foreach($groupe as $row){ ?> <div class="list-group-item checkbox"> <label><input type="checkbox" class="common_selector brand " value="<?php echo $row['group_name'] ?>"><?php echo $row['group_name'] ?></label> </div> <?php } ?> </div> </div> </div> </div> </body> </html> <file_sep><!-- <h2><?php echo $product['lc_style']; ?></h2> --> <html> <link rel="stylesheet" href="https://bootswatch.com/3/flatly/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <body> <div class="container"> <img src="<?php echo $product['image_usr']; ?>" class="float-center"> <ul class="nav nav-tabs "> <h2><?php echo $product['brand_description']; ?></h2> <h3><?php echo $product['display_name_en']; ?></h3> <li class="active"><a data-toggle="tab" href="#home">Overview</a></li> <li><a data-toggle="tab" href="#menu1">Detail</a></li> <li><a data-toggle="tab" href="#menu2">Availabity</a></li> <li><a data-toggle="tab" href="#menu3">Photo</a></li> </ul> <div class="tab-content"> <div id="home" class="tab-pane fade in active"> <p><h3><b>product Information</h3><i><?php echo $product['online_description_en'] ?></i></b></p> <p><b>LC STYLE NUMBER </b> <?php echo $product['lc_style']; ?></p> <p><b>VENDOR </b><?php echo $product['vendor_style']; ?> <p> <b> CATEGORY </b> <?php echo $product['category1']; ?></p> <p><b>BRAND </b> <?php echo $product['brand_name']; ?></p> </div> <div id="menu1" class="tab-pane fade"> <h3>Menu 1</h3> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div id="menu2" class="tab-pane fade"> <h3>Menu 2</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> <div id="menu3" class="tab-pane fade"> <h3>Menu 3</h3> <p>Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> </div> </div> </div> </body> </html> <file_sep><!-- <?php print_r($product); ?> --> <?php $total = 0; foreach($product as $dp) { $total += 1; } $total = (string)$total; ?> <html> <head> <style> .button { background-color: #4CAF50; border: none; color: white; padding: 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; } .button1 {border-radius: 2px; } .button2 {background-color: #e7e7e7; color: black;} </style> <title>fashion</title> <link rel="stylesheet" href="https://bootswatch.com/3/flatly/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <body> <div class="container"> <ul class="nav nav-tabs "> <li class="active"><a data-toggle="tab" href="#menu1">Blogs</a></li> <li><a data-toggle="tab" href="#menu2">Products(<?php echo $total; ?>)</a></li> </ul> <div class="tab-content"> <div id="menu1" class="tab-pane fade in active"> <h3>Menu 1</h3> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> <div id="menu2" class="tab-pane fade "> <?php foreach ($product as $product): ?> <br><br><br><br> <div class="carousel-inner"> <div class="item carousel-item active"> <div class="row"> <div class="col-sm-3"> <div class="thumb-wrapper"> <div class="img-box"> <img src="<?php echo $product['image_usr']; ?>" class="float-left"><br> </div> <div class="thumb-content"> <b><br> <a href="<?php echo site_url('/product/'.$product['lc_style']); ?>"><?php echo $product['brand_description']; ?></a>s <br><?php echo $product['display_name_en']; ?> <br><br> <?php if($product['available_channel']=="Online"): ?> <button class="button button1">online</button> <button2 class="button button2">In-store</button> <?php elseif($product['available_channel']=='Both'): ?> <button class="button button1">online</button> <button1 class="button button1" >In-store</button> <?php elseif($product['available_channel']=='offline'): ?> <button class="button button1" >online</button> <button2 class="button button2" >In-store</button> <?php endif; ?> </b> </div> </div> </div> </div> </div> </div> <?php endforeach; ?> </div> </div> </div> </body> <html> <file_sep><html> <head> <title>fashion</title> <link rel="stylesheet" href="https://bootswatch.com/3/flatly/bootstrap.min.css"> <body> <nav class="navbar navbar-inverse "> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="<?php echo base_url() ?>">Dhm</a> </div> <div id="navbar"> <ul class="nav navbar-nav"> <!-- <form class="form-inline "> <input class="form-control " type="text" placeholder="Search"> <button class="btn btn-secondary " type="submit" >Search</button> </form> --> <?php echo form_open('search/execute_search'); echo form_input(array('name'=>'search')); echo form_submit('search_submit','Search'); ?> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url() ?>">Home</a></li> </ul> </div> </div> </nav><file_sep><?php class Product_model extends CI_Model{ public function __construct(){ $this->load->model('product_model'); } public function get_product($lc_style){ // $this->load->database(); $this->db->order_by('product.lc_style'); $query = $this->db->get_where('product',array('lc_style'=>$lc_style)); return $query->row_array(); // print_r($query->row_array()); } public function get_products(){ // $this->load->database(); $this->db->order_by('product.lc_style'); $query=$this->db->get('product'); return $query->result_array(); } } ?><file_sep> <?php class Product_filter extends CI_Controller { // public function __construct(){ // parent::__construct(); // $this->load->model('product_filter_model'); // } public function index(){ echo "working"; $data['groupe'] = $this->product_filter_model->fetch_filter_type(); // $data['g_name'] = $data['groupe']['group_name']; $this->load->view('product_filter',$data); } } ?><file_sep><?php class Product extends CI_Controller{ // public function __construct(){ // $this->load->model('product_model'); // } public function view($lc_style = NULL){ $data['title'] = 'products'; $data['product'] = $this->product_model->get_product($lc_style); $data['lc_style'] = $data['product']['lc_style']; $this->load->view('templates/header'); $this->load->view('product/view',$data); $this->load->view('templates/footer'); } } ?>
e00e0292bfa87fda88d4f0c8015165d03d44451d
[ "PHP" ]
9
PHP
saurabh-shaw/web-development
ee838f782a2bdf5029da6a68c6c62b35a6b4183f
9297e22f3fc04962e0649e9d93ba91fbff694936
refs/heads/develop
<file_sep># -*- coding: utf-8 -*- ''' Manage nspawn containers ''' # Import python libs from __future__ import absolute_import import os import shutil # Import Salt libs import salt.defaults.exitcodes import salt.utils.systemd __virtualname__ = 'nspawn' WANT = '/etc/systemd/system/multi-user.target.wants/systemd-nspawn@{0}.service' def __virtual__(): ''' Only work on systems that have been booted with systemd ''' if __grains__['kernel'] == 'Linux' and salt.utils.systemd.booted(__context__): return __virtualname__ return False def _arch_bootstrap(name, **kwargs): ''' Bootstrap an Arch Linux container ''' dst = os.path.join('/var/lib/container', name) if os.path.exists(dst): __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL return {'err': 'Container {0} already exists'.format(name)} cmd = 'pacstrap -c -d {0} base'.format(dst) os.makedirs(dst) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL shutil.rmtree(dst) return {'err': 'Container {0} failed to build'.format(name)} return ret def _debian_bootstrap(name, **kwargs): ''' Bootstrap a Debian Linux container (only unstable is currently supported) ''' dst = os.path.join('/var/lib/container', name) if os.path.exists(dst): __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL return {'err': 'Container {0} already exists'.format(name)} cmd = 'debootstrap --arch=amd64 unstable {0}'.format(dst) os.makedirs(dst) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL shutil.rmtree(dst) return {'err': 'Container {0} failed to build'.format(name)} return ret def _fedora_bootstrap(name, **kwargs): ''' Bootstrap a Fedora container ''' dst = os.path.join('/var/lib/container', name) if not kwargs.get('version', False): if __grains__['os'].lower() == 'fedora': version = __grains__['osrelease'] else: version = '21' else: version = '21' if os.path.exists(dst): __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL return {'err': 'Container {0} already exists'.format(name)} cmd = 'yum -y --releasever={0} --nogpg --installroot={1} --disablerepo="*" --enablerepo=fedora install systemd passwd yum fedora-release vim-minimal'.format(version, dst) os.makedirs(dst) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL shutil.rmtree(dst) return {'err': 'Container {0} failed to build'.format(name)} return ret def bootstrap(name, dist=None, version=None): ''' Bootstrap a container from package servers, if dist is None the os the minion is running as will be created, otherwise the needed bootstrapping tools will need to be available on the host. CLI Example:: salt '*' nspawn.bootstrap arch1 ''' if not dist: dist = __grains__['os'].lower() return locals['_{0}_bootstrap'.format(dist)](name, version=version) def enable(name): ''' Enable a specific container CLI Example:: salt '*' nspawn.enable <name> ''' cmd = 'systemctl enable systemd-nspawn@{0}'.format(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: __context__['retcode'] = salt.defaults.exitcode.EX_UNAVAILABLE return False return True def start(name): ''' Start the named container CLI Example:: salt '*' nspawn.start <name> ''' cmd = 'systemctl start systemd-nspawn@{0}'.format(name) ret = __salt__['cmd.run_all'](cmd, python_shell=False) if ret['retcode'] != 0: __context__['retcode'] = salt.defaults.exitcode.EX_UNAVAILABLE return False return True
3693ba329d77b2f2bfc25b1972f31b01d80e14f0
[ "Python" ]
1
Python
s8weber/salt
7f6053a3fbcc7098a1b16f29f85e47e362225266
b0385662cab46bb7c844ccc125bccc6328f39a4b
refs/heads/master
<file_sep>import React, { Component } from 'react' export default class Product extends Component { render() { let { match } = this.props; let name = match.params.name; return ( <h1> Đây là chi tiết sản phẩm : {name} </h1> ) } } <file_sep>import React, { Component } from 'react'; import { Prompt } from 'react-router-dom'; export default class Contact extends Component { constructor(props) { super(props); this.state = { isCheck: true } } onClick = (isCheck) => { this.setState({ isCheck: isCheck }) } render() { return ( <div> Đây là trang liên hệ <button type="button" class="btn btn-default" onClick={() => this.onClick(false)}>Cho phép</button> <button type="button" class="btn btn-default" onClick={() => this.onClick(true)}>Không cho phép</button> <Prompt when={true} message={location => (`Bạn muốn đi đến${location.pathname}`)} /> </div> ) } }
5cd9aaef4d6e0b6a47d0a972f015b867fac1a8fd
[ "JavaScript" ]
2
JavaScript
thinnguyen1888/react-router
0eb74575e0898dbf50208b38ef6e5452f1880f5c
1dd410c0d3079e7883668409ee58a1d9a798334b
refs/heads/master
<file_sep>import { Component, OnInit, OnDestroy } from '@angular/core'; import { LocationService } from '../location.service'; import { Observable, Subscription } from 'rxjs'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-location-info', templateUrl: './location-info.component.html', styleUrls: ['./location-info.component.scss'] }) export class LocationInfoComponent implements OnInit, OnDestroy { public data: Observable<any>; public routeSubscription: Subscription; public id: number; constructor(private locationService: LocationService, private route: ActivatedRoute) { } ngOnInit() { this.showData(); this.getUrlId(); } public showData(): void { this.data = this.locationService.data; } public getUrlId(): void { this.routeSubscription = this.route.children[0].url.subscribe(item => this.id = +item[0].path); } ngOnDestroy() { this.routeSubscription.unsubscribe(); } } <file_sep>import { Injectable } from '@angular/core'; import { AngularFirestore } from '@angular/fire/firestore'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class LocationService { public data: Observable<any>; constructor(private firestore: AngularFirestore) { this.data = this.firestore.collection('locations').valueChanges(); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { LocationService } from './location.service'; import { Subscription, Observable } from 'rxjs'; @Component({ selector: 'app-location', templateUrl: './location.component.html', styleUrls: ['./location.component.scss'] }) export class LocationComponent implements OnInit { public locations: Array<any>; public data: Observable<any>; constructor(private locationService: LocationService) { } ngOnInit() { this.showData(); } public showData(): void { this.data = this.locationService.data; } }
bf1cf4e93d020460905a92a7a113ae57b9a4d029
[ "TypeScript" ]
3
TypeScript
Gusvarov/test-task
2b6782a15dc02de70146ca7fa2de0abc34b21f44
7317c2685f9b629a27e702c4f6e87af750d1da1b
refs/heads/master
<file_sep><?php /*This file declares the functions used to include reoccuring elements like footers and headers*/ $path = $_SERVER['DOCUMENT_ROOT'].'/includes/'; function analytics() { include $GLOBALS['path'].'googleTagManager.php'; } function navbar() { include $GLOBALS['path'].'navbar.php'; } function footer() { include $GLOBALS['path'].'footer.php'; } function favicons() { include $GLOBALS['path'].'favicons.php'; } function css() { include $GLOBALS['path'].'css.php'; } function js() { include $GLOBALS['path'].'js.php'; } function echoGeneralKeywords() { echo 'connectiv8,connectivate,internships,students,projects,paid internships,university'; } ?> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Software Research, GreenCity Initiative"> <meta name="description" content="GreenCity Initiatives is a business development and innovation firm, specializing in sustainable and renewable technologies. GreenCity is developing an urban farm with advanced horticulture systems designed to be operated indoors. In doing this, it needs to know what software could be required to operate, monitor, and control an indoor farm, and what software is currently available to meet that need."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,urban farming,greencity,greencity initiative,software research"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Software Research, GreenCity Initiative</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/processor.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/processor.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Software Research</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$150.00</h2> <h2 class="project-price-narrow hidden-md-up">$150.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">GreenCity Initiatives</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"> GreenCity Initiatives is a business development and innovation firm, specializing in sustainable and renewable technologies. GreenCity is developing an urban farm with advanced horticulture systems designed to be operated indoors. In doing this, it needs to know what software could be required to operate, monitor, and control an indoor farm, and what software is currently available to meet that need. </p> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Meet with the client (<NAME>) to understand the indoor farm's horticulture system and to learn what functionality he is looking for from this software. </li> <li> Research currently available software packages and determine if these meet the company's requirements, or if GreenCity will need to develop the necessary software itself. </li> <li> Submit the report to the client. </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> An understanding of computer software and basic electrical systems </li> <li> An interest in sustainability is an asset </li> <li> The ability to scope a problem, and creatively research solutions </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php $applicationInstructionString = '<span class="project-descriptive-text">Please send your resum&eacute; to </span><a href="mailto:<EMAIL>"><EMAIL></a><span class="project-descriptive-text"> with the subject line "YourName_ProjectName_Application."</span>'; ?> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/security.php'; global $cssPath, $fontAwesomeCssPath; $cssPath = '//'.$_SERVER['SERVER_NAME'].'/css/'; $fontAwesomeCssPath = '//'.$_SERVER['SERVER_NAME'].'/font-awesome/css/'; ?> <!-- bootstrap core css CDN --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> --> <!-- Custom fonts --> <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700,700italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="<?php echo $GLOBALS['fontAwesomeCssPath'] ?>font-awesome.min.css" type="text/css"> <!-- Plugin CSS --> <link rel="stylesheet" href="<?php echo $GLOBALS['cssPath'] ?>animate.min.css" type="text/css"> <!-- Creative CSS --> <link rel="stylesheet" href="<?php echo $GLOBALS['cssPath'] ?>creative.css" type="text/css"> <!-- Custom CSS --> <link rel="stylesheet" href="<?php echo $GLOBALS['cssPath'] ?>connectivate.css?ver=1.5" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src=\"https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js\"></script> <script src=\"https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js\"></script> <![endif]--> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/security.php' ?> <!-- jQuery --> <script src="//<?php echo $_SERVER['SERVER_NAME']?>/js/jquery.js"></script> <!-- Bootstrap Core JavaScript CDN --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.2.0/js/tether.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- Plugin JavaScript --> <script src="//<?php echo $_SERVER['SERVER_NAME']?>/js/jquery.easing.min.js"></script> <script src="//<?php echo $_SERVER['SERVER_NAME']?>/js/jquery.fittext.js"></script> <script src="//<?php echo $_SERVER['SERVER_NAME']?>/js/wow.min.js"></script> <!-- Custom Theme JavaScript --> <script src="//<?php echo $_SERVER['SERVER_NAME']?>/js/creative.js"></script><file_sep><?php /*This file contains functions for quickly generating parts of the Team page*/ function teamBio($name, $position, $image, $bio, $email) { echo "<div class=\"col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-4\"> <div class=\"bio-container-c8\"> <h3>" . $name . "</h3> <h4>" . $position . "</h4> <br/> <div class=\"bio-image-container-c8\" style=\"background-image: url(img/team/" . $image . ");\"> <div class=\"circle-offset-left\"> </div> <div class=\"circle-offset-right\"> </div> <div class=\"bio-image-overlay-c8\">" //. $bio . ."<br/>". "<a href=\"mailto:" . $email . "\"><i class=\"fa fa-envelope-o fa-5x\"></i></a>. </div> </div> </div> </div>"; } function teamBio_alone($name, $position, $image, $bio, $email) { echo "<div class=\"bio-container-c8\"> <h3>" . $name . "</h3> <h4>" . $position . "</h4> <br/> <div class=\"bio-image-container-c8\" style=\"background-image: url(img/team/" . $image . ");\"> <div class=\"circle-offset-left\"> </div> <div class=\"circle-offset-right\"> </div> <div class=\"bio-image-overlay-c8\">" //. $bio . ."<br/>". "<a href=\"mailto:" . $email . "\"><i class=\"fa fa-envelope-o fa-5x\"></i></a>. </div> </div> </div>"; } ?><file_sep><?php /*This file contains functions for quickly creating project cards*/ $projectPath = $_SERVER['DOCUMENT_ROOT'].'/projects/'; $imagePath = $_SERVER['DOCUMENT_ROOT'].'/img/project/'; function openProject($projectName, $projectImage, $projectPhpPage, $projectCompany, $projectDescription) { echo "<div class=\"col-xs-12 col-sm-12 col-md-6 col-lg-4\"> <a href=\"" . $GLOBALS['projectPath'] . $projectPhpPage . "\" class=\"project-card-link\"> <div class=\"card card-inverse project-card\"> <img class=\"card-img-top project-card-img-top\" img src=\"" . $GLOBALS['imagePath'] . $projectImage . "\" alt=\"Card image cap\" /> <div class=\"card-block text-center\"> <h3 class=\"card-title\">" . $projectName . "</h3> <h4 class=\"card-subtitle\">" . $projectCompany . "</h4> <p class=\"card-text\">" . $projectDescription . "</p> </div> </div> </a> </div>"; } ?><file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Logo Design, MilleniLink"> <meta name="description" content="MilleniLink Corporation is a new company looking for a logo to represent its brand. This company provides targeted job matching for co-ops, interns, and post-graduates, incorporating technology skills across a wide span of industries."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,MilleniLink corporation,Sabe mpofu,design,logo design,marketing"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Logo Design, MilleniLink</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/business.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/business.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Logo Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$200.00</h2> <h2 class="project-price-narrow hidden-md-up">$200.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">MilleniLink Corporation</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"><NAME>, a Masters of Entrpreneuship and Innovation Candidate at Queen's University, is starting a brilliant new venture with MilleniLink. Like Connectiv8, he sees the potential for improved practical education.The goal is to connect technologically skilled students with co-ops, internships and post-graduate positions where they can apply their skills across diverse industry roles. </p> <p class="project-descriptive-text">To kick off this project, Sabe needs a logo that can represent this brand! This is an opportunity to create a symbol that will be at the forefront of all this company's work for a good deal of time to come. Show off your skills!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Work closely with a professional client to combine your creativity with their vision. </li> <li> Practice using different design tools and techniques </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with Sabe to learn about his business's brand and vision. </li> <li> Develop three creative logo designs for Sabe based on this information. </li> <li> Review the designs with Sabe and finalize a single design. </li> <li> Complete the finishing touches. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Creativity </li> <li> Design experience </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, Kingston Brewing Company"> <meta name="description" content="Kingston Brewing Company may be the oldest brew pub in Ontario, but that doesn't mean they can't keep up with the times! Help them out by revamping their website."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,Kingston Brewing Company,web design,web development"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, Kingston Brewing Company</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/folded-laptop.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/folded-laptop.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$340.00</h2> <h2 class="project-price-narrow hidden-md-up">$340.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Kingston Brewing Company</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Kingston Brewing Company may be the oldest brew pub in Ontario, but that doesn't mean it can't keep up with the times! The pub wants to update the site to a modern design, and to do so using Wordpress or a similar platform that would enable it to be easily updated by the pub staff and management. The overall goals are to generate more interest in the pub, and to highlight the many events that take place throughout the year. Check out the current site at <a href="http://www.kingstonbrewing.ca/">kingstonbrewing.ca</a>. We know you can improve it!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Learn to work directly with a local client </li> <li> Use your knowledge of web development to guide the client to an effective site design </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with the Kingston Brewing Company management to discuss the the goals of this project </li> <li> Plan the site to meet the company's needs of design and customizability </li> <li> Develop the site </li> <li> Coach the management team through basic maintenance and editing procedures </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience with web design and development </li> <li> Creativity and an eye for attractive web design </li> <li> Strong communication and team work skills </li> </ul> <p><strong>This project accepts applications on a rolling basis, and could be closed at any time.</strong></p> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/security.php' ?> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-57x57.png" rel="apple-touch-icon" sizes= "57x57"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-60x60.png" rel="apple-touch-icon" sizes= "60x60"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-72x72.png" rel="apple-touch-icon" sizes= "72x72"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-76x76.png" rel="apple-touch-icon" sizes= "76x76"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-114x114.png" rel="apple-touch-icon" sizes= "114x114"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-120x120.png" rel="apple-touch-icon" sizes= "120x120"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-144x144.png" rel="apple-touch-icon" sizes= "144x144"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-152x152.png" rel="apple-touch-icon" sizes= "152x152"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/apple-touch-icon-180x180.png" rel="apple-touch-icon" sizes= "180x180"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/favicon-32x32.png" rel="icon" sizes="32x32" type= "image/png"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/android-chrome-192x192.png" rel="icon" sizes="192x192" type= "image/png"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/favicon-96x96.png" rel="icon" sizes="96x96" type= "image/png"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/favicon-16x16.png" rel="icon" sizes="16x16" type= "image/png"> <link href="//<?php echo $_SERVER['SERVER_NAME']?>/ic/manifest.json" rel="manifest"> <meta content="#da532c" name="msapplication-TileColor"> <meta content="//<?php echo $_SERVER['SERVER_NAME']?>/ic/mstile-144x144.png" name="msapplication-TileImage"> <meta content="#ffffff" name="theme-color"><file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Marketing Project"> <meta name="description" content="A youth entrepreneurship program will be happening this summer, and the organizers want to market to post-secondary students. Help them out!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,youth entrepreneurship, entrepreneurship, marketing"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Marketing Project</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/iphone.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/iphone.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Marketing Project</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$200</h2> <h2 class="project-price-narrow hidden-md-up">$200</h2> </div> </div> </div> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"> A youth entrepreneurship program will be happening this summer! Help them promote this program to post-secondary students. </p> <p class="project-descriptive-text">Please inquire for more information. </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Master social media sales strategies </li> <li> Learn about youth entrepreneurship </li> <li> Contribute your own ideas </li> </ul> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Meet with the program provider to learn about the goals of the marketing project. </li> <li> Plan a focused, tactical approach to the social media campaign. </li> <li> Implement the plan within an agreed upon period of time. </li> <li> Maintain an ethical approach to online social media communications. </li> <li> With approval from the program provider, implement the plan and spread the word! </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Self-starter </li> <li> Outgoing and personable </li> <li> Maintain a diverse network within the student community </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, Wellness Simplified"> <meta name="description" content="Wellness Simplified is a nutrition coaching practice, empowering individuals to prioritize their health through food. They want to add some functionality to their current site."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,wellness simplified,web design,web development,nutrition"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, Wellness Simplified</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/laptop-coffee.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/laptop-coffee.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$450.00</h2> <h2 class="project-price-narrow hidden-md-up">$450.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Wellness Simplified</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"> Wellness Simplified is a food-centric nutrition coaching practice that empowers individuals to prioritize their health and well-being starting in the kitchen. They go beyond the consultation room and bring the science of nutrition full-circle by educating, encouraging and equipping individuals with the hands-on food skills to make healthy eating the easier choice. </p> <p class="project-descriptive-text"> The goal of this project is to update the site while maintaining the general look and feel as it stands now (see <a href="http://www.nutritionwellnesssimplified.com">www.nutritionwellnesssimplified.com</a>). Generally, they would like an appointment scheduling feature, a new home page with an embedded YouTube video, a search feature, and a new blog-format for displaying recipes. If this sounds like a piece-of-cake, this is the perfect project for you! </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Learn new recipes and culinary tricks for healthy living </li> <li> Discover more about what constitutes a healthy diet </li> <li> Generate technical solutions to a real client's problem </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with the head of Wellness Simplified to review the project requirements </li> <li> Perform some cosmetic changes (eg. new images) </li> <li> Add a "home" landing page with an embedded YouTube video </li> <li> Implement an appointment scheduler on the site </li> <li> Convert the recipes from attached PDFs into a blog format, with integrated search functionality </li> <li> Once complete, perform a detailed handoff of the new systems with Amanda to help her with future updates </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience with web design and development </li> <li> Creativity and a modern artistic flair </li> <li> A passion for food and nutrition </li> <li> Familiarity with current food trends and blogs is a bonus </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/loading.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/loading.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Social Media Marketing</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$100.00</h2> <h2 class="project-price-narrow hidden-md-up">$100.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">CDK Walk In Clinic</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">CDK would like to improve its online presence to aid in its goal of increasing outreach and marketing to different demographics in the Kingston area (Queen's and Downtown Kingston specifically). The company needs someone to continuously run their current social-media pages (Facebook) and potentially build new ones (Twitter, Instagram, etc.) if it makes sense to do so.</p> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with <NAME> to discuss current initiatives, expectations, and goals for online content </li> <li> Improve and manage CDK's Facebook page and build other platforms (Twitter, Instagram, etc.) </li> <li> Create online content to be continuously posted on these pages </li> <li> Share and market the pages so that 200 likes are reached on the Facebook page </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Marketing experience </li> <li> An in-depth knowledge of social media platforms </li> <li> Graphic design skills an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Businesses"> <meta name="description" content="Connect with talented students and improve your business!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Businesses</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <header class="businesses"> <div class="header-content"> <div class="header-content-inner"> <h1>Connecting Businesses<br/>with Talent</h1> <hr> <p style="color: white;">Bringing the enthusiasm and creativity of young professionals to your work.</p> <a href="#what-we-do" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header> <section id="benefits"> <div class="container text-xs-center"> <div class="row"> <div class="col-lg-10 offset-lg-1 text-xs-center"> <h2> What Are the Benefits? </h2> <hr /> <ul class="text-xs-left business-list"> <li><strong>Capitalize</strong> on the interest and the skills of young professionals looking to gain experience in the workplace.</li> <li><strong>Inexpensively research</strong> various solutions to internal problems, and ways to increase efficient and sustainable practices.</li> <li><strong>Access innovative solutions</strong> through the creative, open-minds of students.</li> <li><strong>Develop relationships</strong> with young professionals, testing out talent while widening your hiring reach.</li> <li><strong>Engage in something greater</strong> than yourselves – by providing projects and mentoring students.</li> </ul> </div> </div> </div> </section> <section class="bg-primary with-shadow" id="what-we-do"> <div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2 text-xs-center"> <h2 class="section-heading">What We Do For You</h2> <hr class="light"> <p> Businesses, entrepreneurs and non-profits can all benefit from the platform that Connectiv8 provides. <br><br>Students represent a massive, untapped resource of driven and capable young professionals. Facilitating the connection between business and student, or organization and student, is a simple but powerful arrangement. <br><br> Businesses and organizations can offer up projects to students; these could be projects that you do not have the time or resources to work on, or perhaps you want a fresh take on the challenge. By allowing students to take on these projects for you, you can instigate growth, increase efficiency and drive profits. </p> </div> </div> </div> </section> <section id="process"> <div class="container"> <div class="row"> <div class="col-lg-12 text-xs-center"> <h2 class="section-heading">The Process</h2> <hr class="primary"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-3 col-md-3 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-lightbulb-o wow bounceIn text-primary"></i> <h3>Inquire</h3> <p class="text-muted">It could require anything from a week to several months of work, but as soon as you identify a need, get in touch!</p> </div> </div> <div class="col-lg-3 col-md-3 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-paper-plane wow bounceIn text-primary" data-wow-delay=".1s"></i> <h3>Distribute</h3> <p class="text-muted">Define your objectives, set your price, and spark student interest.</p> </div> </div> <div class="col-lg-3 col-md-3 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-users wow bounceIn text-primary" data-wow-delay=".2s"></i> <h3>Connect</h3> <p class="text-muted">Your project sounds brilliant, and students want to help! We’ll help you find the perfect match.</p> </div> </div> <div class="col-lg-3 col-md-3 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-line-chart wow bounceIn text-primary" data-wow-delay=".3s"></i> <h3>Evaluate</h3> <p class="text-muted">Your student’s creative talents have rocketed past your expectations! Why don’t you do this for all your projects?</p> </div> </div> </div> </div> </section> <section id="email" class="bg-dark with-shadow"> <div class="container text-xs-center"> <div class="call-to-action"> <h2>Interested?</h2> <hr class="light" /> <p>Fire an email to Paul, our head of sales! <br /> He'll be happy to consult with you to create projects specific to your business needs.</p> <a href="mailto:<EMAIL>" class="btn btn-default btn-xl">Email Paul</a> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/limestonemusic-mic.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/limestonemusic-mic-small.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Sound Production Contacts Report</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$200.00</h2> <h2 class="project-price-narrow hidden-md-up">$200.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Limestone Music</p> <p class="project-descriptive-text">Project due: January 17th</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Limestone music, through its sound production business Showcall, would like to become more involved with events in the Queen’s community. To accomplish this Showcall needs to be made aware of the events taking place, and who to contact in regards to them.</p> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Conduct research into different music events happening at Queen’s and in the Kingston area. </li> <li> Prepare a report outlining events that would require sound production. Organizers responsible for running said events should be contacted to gauge interest, and to acquire contact information to be included in the report. </li> <li> Report should include dates, locations, event outlines and contact information of organizers. </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Passion for music, live shows, and music production </li> <li> Outgoing personality and effective reach in the Queen’s community </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, 1000 Island Soap Co."> <meta name="description" content="1000 Islands Soap Co., having recently refurbished their website, is looking to add a blog in order to attract more users."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,1000, island, soap, co., blog, web, design, development"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, 1000 Island Soap Co.</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/webdesign.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/webdesign.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$150.00</h2> <h2 class="project-price-narrow hidden-md-up">$150.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">1000 Island Soap Co.</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">A small family business located in Kingston, 1000 Island Soap Company specializes in skincare products. After recently refurbishing their website, they would look to add a blog in order to attract more users. Your job is to create it and add a button on the main page that links to it, and to add some social media integration.</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Create a professional blog </li> <li> Intergrate social media into a website </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Create a blog that is easily editable </li> <li> Add a "Blog" button to main website that links to the blog, hosted on the same domain </li> <li> Add Facebook and Twitter buttons at the bottom of every www.1000islandssoapco.com page </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> HTML and CSS knowledge </li> <li> Javascript knowledge an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Program Design, Cloud Nine Guides"> <meta name="description" content="Cloud Nine Guides, a Mountain School and Internationally Certified Guide Service located in the Canadian Rockies, would like a student to design a new Program Guide for tourists and other potential clients."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,cloud nine guides,mountain school,mountaineering,rocky mountains,rockies,design,program guide"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Program Design, Cloud Nine Guides</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/mountains.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/mountains.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Program Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$375.00</h2> <h2 class="project-price-narrow hidden-md-up">$375.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Cloud Nine Guides</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"> <a href="http://www.cloudnineguides.com/">Cloud Nine Guides</a> is a Mountain School and Internationally Certified Guide Service located in the Canadian Rockies, and they cover activities from rock climbing to ski touring. They would like a student to design a template for a new Program Guide for tourists and other potential clients, that could be available in hotels and from their business locations. <br/> <br/> What exactly is a program guide? An example can be found <a href="https://issuu.com/yamnuska.mountain.adventures/docs/yamnuska_programguide_2016_5de54cef83a7a9">here</a>. <br/> <br/> If you're interested in hiking, rock-climbing, skiing, mountaineering or just want to do some design, this is a brilliant opportunity for you to make some contacts, learn about these activities, and show-off your talents. </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Create attractive marketing material for a real business </li> <li> Discover new outdoor opportunities available to you in the Canadian Rockies </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Contact Cloud Nine Guides to discuss their business, target market, and branding. </li> <li> Review some example guides such as <a href="https://issuu.com/yamnuska.mountain.adventures/docs/yamnuska_programguide_2016_5de54cef83a7a9">this one</a> to get a feel for what a Prgoram Guide looks like. </li> <li> Develop a distinctive template with Cloud Nine Guides branding for about a 20-page guide that they can add text and images to as needed. </li> <li> Refine the design based on feedback from Cloud Nine Guides. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience with Photoshop, Illustrator, or similar </li> <li> Design and Marketing knowledge or experience </li> <li> Creativity, and a passion for mountain activities </li> <li> Previous sponsorship package or promo material design a plus </li> </ul> <p><strong>Applications are now closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php global $httpConnection; $httpConnection = 'http://'; if (isset($_SERVER['HTTPS'])) { $httpConnection = 'https://'; } function getHttpConnectionString() { return $GLOBALS['httpConnection']; } ?> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Design, Harambe Escapes"> <meta name="description" content="Harambe Escapes is a new, multi-platform game which is still in development. The developer needs a graphic designer to create images for the application. The app is already complete, so once the images are in it can be released!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,graphic design,game design,games,apps,harambe,harambe escapes"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Design, Harambe Escapes</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/gorilla.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/gorilla.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Graphic Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$60.00</h2> <h2 class="project-price-narrow hidden-md-up">$60.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Harambe Escapes</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Harambe Escapes is a new Android and iPhone game which is currently in development by a Queen's first-year student. The game is essentially complete, however it needs new graphics! The developer is open to new character ideas, themes, etc. There are two categories of images needed: </p> <ol class="project-descriptive-text"> <li> Detailed Images (9 total) - These include the animal faces and bodies </li> <li> Easy to Medium Images (13 totoal) - These range from a green background, to a sound button. Generally smaller and less detailed. </li> </ol> <p class="project-descriptive-text">Send in an application if you're interested!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Learn about images needed for app and game development. </li> <li> Learn to create animations using multiple photos. </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with the developer and discuss the image requirements. </li> <li> Produce the images, making updates based on feedback. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Digital design experience </li> <li> Creativity </li> <li> Animation experience a plus </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/1000islandsoap-webdev.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/1000islandsoap-webdev.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <h2 class="project-title">Web Development</h2> <p class="project-descriptive-text" style="margin-bottom: 5px;">1000 Island Soap Company</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">1000 Island Soap Company is ready to create a new look for their website, while enhancing the user-interface to make it more customer friendly. In particular, 1000 Island Soap Co. would like to make two improvements:</p> <ol class="project-descriptive-text"> <li> Allow website users to purchase products as guests </li> <li> Improve the general efficiency and layout of the website </li> </ol> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Meet with the client, <NAME>, to discuss the vision for the website </li> <li> Create a brand new website meeting Jackie’s specifications </li> <li> Regularly perform updates on the website to ensure it consistently performs as desired </li> <li> Develop a fully functional and easy-to-use e-commerce shopping cart </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Website development experience </li> <li> Strong research and design skills </li> <li> Graphic design experience a plus </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include $_SERVER['DOCUMENT_ROOT'].'/functions/projectCardGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Projects"> <meta name="description" content="View Connectiv8's open and recent projects."> <meta property="og:site_name" content="Connectiv8"/> <meta property="og:title" content="Projects"/> <meta description="og:description" content="View Connectiv8's open and recent projects."/> <meta property="og:image" content="img/Logos/C8_Logo_version_1.2.png" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://connectiv8.com/projects.php" /> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Projects</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section class="bg-primary with-shadow text-xs-center" id="header" style="margin-top: 50px"> <div class="container"> <h1 class="projects" style="text-transform: uppercase; margin-top:30px; margin-bottom: 30px;">Projects</h1> <hr class="light"> <h3 style="margin: 40px 0px 40px 0px; font-size: 20px;"> Don't see something you're interested in? Fill out this <a link="black" href="https://docs.google.com/forms/d/e/1FAIpQLSc1vtXuNZGL1yMUBeP9Ie3H2-CP4o1ivyxIyHeCZBbB2B481g/viewform#responses"><font color= "black">survey</font></a> and we will get a better sense of what you want and contact you when something comes up! </h3> </div> </section> <section class="with-bottom-shadow" id="projects"> <div class="container"> <div class="text-xs-center"> <h2 class="">Open Projects</h2> </div> </div> <div class="container"> <div class="row"> <div class="center"> <div class="card-deck project-card-deck"> <!-- Border for when only two cards visible --> <!-- <div class="hidden-md-down col-lg-2"></div> --> <!-- Border for when only one card visible --> <!-- <div class="hidden-sm-down col-lg-2"></div> --> <!-- <div class="hidden-md-down col-lg-2"></div> --> <div class="col-xs-10 offset-xs-1 col-sm-10 offset-sm-1 offset-md-0 col-md-6 offset-lg-0 col-lg-4"> <?php openProjectCard("Android App Development </br>Front End", "desk.jpg", "estart-front.php", "E-start", "E-start is a new venture from a current student at Queen’s Masters of Entrepreneurship and Innovation program. This company is an educational video content provider for preschool to high school age kids in Nigeria. This project will focus on the front end development of this app.", "Rolling Applications", '1750 plus equity'); ?> </div> <div class="col-xs-10 offset-xs-1 col-sm-10 offset-sm-1 offset-md-0 col-md-6 offset-lg-0 col-lg-4"> <?php openProjectCard("Android App Development </br>Back End", "iphone.jpg", "estart-back.php", "E-start", "E-start is a new venture from a current student at Queen’s Masters of Entrepreneurship and Innovation program. This company is an educational video content provider for preschool to high school age kids in Nigeria. This project will focus on the back end development of this app.", "Rolling Applications", '1750 plus equity'); ?> </div> <div class="col-xs-10 offset-xs-1 col-sm-10 offset-sm-1 offset-md-0 col-md-6 offset-lg-0 col-lg-4"> <!-- <div class="hidden-sm-down col-lg-2"></div> --> <?php openProjectCard("Web and App Development", "laptop-coffee.jpg", "cozii.co-webdev.php", "Cozii.co", "Cozii.co is a new venture aiming to deliver a two-sided marketplace platform - web and mobile - to book/request home maintenance services in real-time. This amazing payment and equity based opportunity requires two students to collaborate on web and app development.", "Rolling Applications", '1000+ and Equity'); ?> </div> <div class="col-xs-10 offset-xs-1 col-sm-10 offset-sm-1 offset-md-0 col-md-6 offset-lg-4 col-lg-4"> <!-- <div class="hidden-sm-down col-lg-2"></div> --> <?php openProjectCard("Product Sales", "beerflight.jpg", "gananoquebrewingcompany-brandambassadors2.php", "Gananoque Brewing Co.", "Gananoque Brewing Company (GBC), a local micro-brewery, wants to sell some kegs! People are always throwing events. How hard is this going to be?", "Rolling Applications", '20 / keg'); ?> </div> <!-- Border for when only two cards visible --> <!-- <div class="hidden-md-down col-lg-2"></div> --> <!-- Border for when 3 or more cards visible --> <!-- <div class="col-xs-12 col-sm-12 col-md-6 col-lg-4"> --> <!-- Heading --> <!--<div class="col-xs-10 offset-xs-1 col-sm-10 offset-sm-1 offset-md-0 col-md-6 offset-lg-0 col-lg-4"> --> </div> </div> </div> </div> </section> <section class="bg-primary with-bottom-shadow closed-projects" id="closed-projects"> <div class="container"> <div class="text-xs-center"> <h2 class="">Closed Projects</h2> </div> </div> <div class="container"> <div class="row"> <div class="center"> <div class="card-deck project-card-deck"> <?php closedProjectCard("Merchandise Graphic Design", "IMI-pic-wide.jpg", "IMI-design.php", "Imprint Merchandising Inc."); ?> <?php closedProjectCard("Web Development", "webdesign.jpg", "pivot-webdesign.php", "Pivot"); ?> <?php closedProjectCard("Graphic Design", "gorilla.jpg", "harambeescapes-design.php", "Harambe Escapes"); ?> <?php closedProjectCard("Program Guide", "mountains.jpg", "cloudnineguides-programdesign.php", "Cloud Nine Guides"); ?> <?php closedProjectCard("Frosh Week & Events Coordinator", "coins.jpg", "drugsmart-events.php", "DrugSmart Pharmacy"); ?> <?php closedProjectCard("Web Development", "laptop.jpg", "dharanihealingarts-webdev.php", "Dharani Healing arts"); ?> <?php closedProjectCard("Web Development", "webdesign.jpg", "1000islandsoapsblog-webdev.php", "1000 Islands Soap Co."); ?> <?php closedProjectCard("Web Development", "folded-laptop.jpg", "kingstonbrewco-webdev.php", "Kingston Brewing Company"); ?> <?php closedProjectCard("Web Development", "laptop-coffee.jpg", "wellnesssimplified-webdev.php", "Wellness Simplified"); ?> <?php closedProjectCard("Sales Project", "business2.jpg", "windmills-conferencecontactinformation.php", "Windmills Restaurant and Catering"); ?> <?php closedProjectCard("Marketing Project", "iphone.jpg", "anonymous-marketing.php", "Youth Entrepreneurship Program"); ?> <?php closedProjectCard("Logo Design", "business.jpg", "millenilink-logodesign.php", "MilleniLink Corporation"); ?> <?php closedProjectCard("Design and Branding", "desk.jpg", "wildandtame-design.php", "Wild and Tame"); ?> <?php closedProjectCard("Web Development", "laptop.jpg", "wildandtame-webdev.php", "Wild and Tame"); ?> <?php closedProjectCard("Social Media Coaching", "loading.jpg", "wildandtame-socialmedia.php", "Wild and Tame"); ?> <?php closedProjectCard("Software Research", "processor.jpg", "greencity-softwareresearch.php", "GreenCity Initiative"); ?> <?php closedProjectCard("Brand Ambassadors", "beerflight.jpg", "gananoquebrewingcompany-brandambassadors.php", "Gananoque Brewing Company"); ?> <?php closedProjectCard("Web Design and Development", "webdesign.jpg", "johnsdeli-webdev.php", "<NAME>"); ?> <?php closedProjectCard("Business Efficiency Consultation", "solarpanels.jpg", "cdk-businessefficiency.php", "CDK Clinic"); ?> <?php closedProjectCard("Social Media Marketing", "loading.jpg", "cdk-socialmedia.php", "CDK Clinic"); ?> <?php closedProjectCard("Marketing Idea Generation", "business.jpg", "grahamspharmacy-marketingideageneration.php", "<NAME>"); ?> <?php closedProjectCard("TV Advertisement Sales", "coins.jpg", "cdk-advertisementsales.php", "CDK Clinic"); ?> <?php closedProjectCard("Marketing Project", "business.jpg", "cdk-marketingideageneration.php", "CDK Clinic"); ?> <?php closedProjectCard("Web Development and Marketing", "grahamspharmacy-webdevelopment-small.jpg", "grahamspharmacy-webdevelopment.php", "Graham's Pharmacy"); ?> <?php closedProjectCard("Department Catering Sales", "windmills-wine.jpg", "windmills-departmentcateringsales.php", "Windmills Restaurant and Catering"); ?> <?php closedProjectCard("Web Design", "faciocorporation-small.jpg", "faciocorporation-webdev.php", "Facio Corporation"); ?> <?php closedProjectCard("Web Development", "seacandytackle-banner.jpg", "seacandytackle-webdev.php", "SeaCandy Tackle"); ?> <?php closedProjectCard("Sound Production Contacts Reports", "limestonemusic-mic-small.jpg", "limestonemusic-soundproduction.php", "Limestone Music"); ?> <?php closedProjectCard("Retirement Home Sales and Marketing", "grahamspharmacy-retirementmarketing-small.jpg", "grahamspharmacy-retirementhomemarketing.php", "<NAME>"); ?> <?php closedProjectCard("Social Media Management", "barbershop-small.jpg", "generationsbarbershop-socialmedia.php", "Generations Barbershop"); ?> <?php closedProjectCard("Social Media Management", "grahams-pharmacy-street-small.jpg", "grahamspharmacy-socialmedia.php", "<NAME>"); ?> <?php closedProjectCard("Web Development and Marketing", "grahamspharmacy-webdevelopment-small.jpg", "grahamspharmacy-webdevelopment.php", "Graham's Pharmacy"); ?> <?php closedProjectCard("Urban Farming Capsule Re-Design", "greencity-urbanfarming-small.jpg", "greencity-urbanfarming.php", "GreenCity Initiatives"); ?> <?php closedProjectCard("Web Development", "1000islandsoap-webdev-small.jpg", "1000islandsoaps-webdev.php", "1000 Island Soap Company"); ?> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> <script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true"></script> <script type="text/javascript" src="/js/cookies.min.js"></script> <script type="text/javascript" src="/js/registerInit.min.js"></script> <script type="text/javascript" src="/js/cardHeights.min.js"></script> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Design, Imprint Merchandising Inc."> <meta name="description" content="Imprint Merchandising Inc. is looking for a full time designer and store manager to join the team as a partner in the company. The chosen designer will go through a 1-2 month testing period, developing different designs throughout that time on a contractual basis, before eventually being given equity in the company as a partner assuming that the goals of the company and it’s partners have been met."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,graphic design,"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Design, Imprint Merchandising Inc.</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/IMI-pic.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/IMI-pic-wide.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Merchandise Graphic Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$200.00 + Equity</h2> <h2 class="project-price-narrow hidden-md-up">$200.00 + Equity</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Imprint Merchandising Inc.</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Imprint Merchandising Inc. is a new start-up that builds and manages e-commerce merchandise stores for social media stars. After having built our clientele base to 3 YouTubers and having hit $50k in sales since launch date 3 months ago, we’ve proven our business model and are looking to expand quickly to develop the clientele base. </p> <p class="project-descriptive-text">Imprint Merchandising Inc. is looking for a designer and store manager to join the team as a <b>partner</b> in the company. The chosen designer will go through a 1-2 month testing period, developing different designs throughout that time on a contractual basis, before eventually being given <b>equity</b> in the company as a partner assuming that the goals of the company and it’s partners have been met. </p> <p class="project-descriptive-text">Send in an application if you're interested!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Develop a solid and deep understanding of Shopify and the incredible possibilities it provides </li> <li> Design for YouTube stars with hundreds of thousands of subscribers </li> <li> Learn how to manage and rapidly build a new company looking to scale quickly </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Develop 3-5 designs (t-shirts, coffee mugs, blankets etc) for November - December 2016 </li> <li> Develop the brand of Imprint Merchandising Inc., and the way it will show itself off to future clientele </li> <li> Manage 3+ stores and the merchandise available through suppliers </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Incredible design skills. </li> <li> On time. Always. </li> <li> A little bit quirky. </li> </ul> <p><strong>Applications are now closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep>function resizeCards(cards) { //re-auto height for (var i = 0; i < cards.length; i++) { cards[i].style.height = "auto"; } //find maximum height var maxheight = 0; for (var i = 0; i < cards.length; i++) { if (cards[i].offsetHeight > maxheight) maxheight = cards[i].offsetHeight } // Make sure the first card has auto width cards[0].style.width = 'auto'; //set cards to this height for (var i = 0; i < cards.length; i++) { cards[i].style.height = maxheight + 'px'; // Set all cards to the same width as the first card in the deck if (i != 0) { cards[i].style.width = (cards[0].offsetWidth) + 'px'; } if ($(cards[i]).hasClass("closed-card")) { var imageUrl = cards[i].style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2') .split(',')[0]; var image = new Image(); image.src = imageUrl; var width = image.width; var height = image.height; if ((height / width) > (maxheight / cards[i].clientWidth)) { cards[i].style.backgroundSize = cards[i].clientWidth +'px auto'; } else { cards[i].style.backgroundSize = 'auto ' + maxheight + 'px'; } var shadedDiv = cards[i].getElementsByClassName("closed-project-card-overlay"); shadedDiv[0].style.height = maxheight + 'px'; } } } function getCards() { var cards = document.getElementsByClassName("card-size1"); var closedCards = document.getElementsByClassName("closed-card"); resizeCards(cards); resizeCards(closedCards); window.onresize = function (event) { resizeCards(cards); resizeCards(closedCards); }; } getCards(); <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, <NAME>"> <meta name="description" content="<NAME>i is looking to create a static webpage to advertise its location, and showcase its weekly specials and meat package service."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,<NAME>,web design,web development"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, <NAME></title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/webdesign.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/webdesign.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$250.00</h2> <h2 class="project-price-narrow hidden-md-up">$250.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;"><NAME></p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"><NAME> is looking to create a static webpage to advertise its location, and showcase its weekly specials and meat package service.</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Create a professional, static web site from scratch </li> <li> Demonstrate your design skills </li> <li> Develop problem scoping and solving experience with a real-world client </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with <NAME> to discuss website vision and specifications </li> <li> Design the website for John's Deli </li> <li> Setup a web server and publish the site </li> <li> Show Gib how to access the server and update weekly specials and other site information. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience with web design and development </li> <li> Creativity and an eye for clear, attractive design </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Design, Wild and Tame"> <meta name="description" content="Wild and Tame, a sustainability consulting company, is looking for a student to develop a fresh new look and marketing style for itself."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,wild and tame,david see,shari hughson,design,marketing"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Design, Wild and Tame</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/desk.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/desk.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Design and Rebranding</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$375.00</h2> <h2 class="project-price-narrow hidden-md-up">$375.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Wild and Tame</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"><NAME> and <NAME> inspire, teach and consult for people and communities to create self-reliant and self-sustaining lifestyles. They base this work on their experience living off the land in the remote wilderness of British Columbia. To kick their company off, they need a fresh brand, and a creative marketing strategy.</p> <p>Important: You will be working very closely with another student, focusing on the web development aspects outlined <a href="wildandtame-webdev.php">here</a>. If you know someone you would like to work with, mention each other when you both apply!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Develop a new, lasting brand for a local company </li> <li> Learn social media marketing strategies </li> <li> Work closely with a web developer to implement your own web design </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with David and Shari to discuss their business and their goals. </li> <li> Design for them a manageable website with a landing page, an about page, photos, and a blog. </li> <li> Use your own creative flare to create a new company brand and logo. </li> <li> Write your own marketing content, and develop a social media marketing strategy. </li> <li> Go over your plans with David and Shari as you go, to ensure things align with their expectations. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience with web design </li> <li> Marketing and branding knowledge </li> <li> Creativity and motivation </li> <li> Strong communication and teamwork skills </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/grahamspharmacy-webdevelopment.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/grahamspharmacy-webdevelopment.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development and Marketing</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$100.00</h2> <h2 class="project-price-narrow hidden-md-up">$100.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Graham's Pharmacy</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Generate ideas to improve the Graham’s Pharmacy website’s functionality and features. The overall goal is to improve website traffic and the number of clicks on online advertisements for the pharmacy. This is a chance to challenge your design and marketing skills!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Investigate web design and online user experience </li> <li> Demonstrate marketing creativity meeting the needs of a local business </li> <li> Develop problem scoping and solving experience with a real-world client </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Discuss the functionalities and features of the current website with <NAME> </li> <li> Generate and write a report summarizing a list of ideas to improve the website and its traffic </li> <li> Determine the most effective way to market the pharmacy online, this may involve redesigning the current website and ad banner (placed on website pages) in the Kingston area </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Social media proficiency </li> <li> Promotion and advertising experience a plus </li> <li> Graphic design an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php'; ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/teamPageGenerator.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - The Team"> <meta name="description" content="Meet the team bringing Connectiv8 together."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,team,bio,bios,<NAME>,<NAME>,<NAME>,scott mctavish"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - The Team</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section id="header" style="margin-top: 20px; padding-bottom: 0px;"> <div class="banner-container"> <div class="banner-edge banner-edge-left hidden-sm-down"> </div> <div class="banner-fold banner-fold-left hidden-sm-down"> </div> <!-- Regular banner --> <div class="hidden-sm-down banner"> <h1 style="margin-bottom: 0.3em !important; margin-top: 0.3em;">THE TEAM</h1> </div> <!-- Mobile banner --> <div class="hidden-md-up banner banner-small"> <h1 style="margin-bottom: 0.3em !important; margin-top: 0.3em;">THE TEAM</h1> </div> <div class="banner-fold banner-fold-right hidden-sm-down"> </div> <div class="banner-edge banner-edge-right hidden-sm-down"> </div> </div> <div class="container"> <div class="row"> <?php teamBio("<NAME>", "Director of Sales", "pauleveritt_new.jpg", "<p>WILL SELL YOU A PENCIL.<br/>WILL DO IT WITH AN AWKWARD LAUGH.</p>", "<EMAIL>"); teamBio("<NAME>", "Director of IT", "morganroff_new.jpg", "<p>HE DRINKS A LOT OF TEA.<br/>HE'S PRACTICALLY A TEAPOT.</p>", "<EMAIL>"); teamBio("<NAME>", "Director of Marketing", "samlew_new.jpg", "<p>KNOWN FOR DANCING, PHOTOGRAPHY, AND TRAVEL.<br/>AND HER LAST NAME.</br><NAME> BUT DIFFERENT.</p>", "<EMAIL>"); teamBio("<NAME>", "Director of Operations", "andrewcimino.jpg", "", "<EMAIL>"); teamBio("<NAME>", "IT Team", "sashakuznetsov_new.jpg", "<p>PART TIME CK UNDERWEAR MODEL.<br/>FULL TIME IT EXECUTIVE AT CONNECTIV8.</p>", "<EMAIL>"); teamBio("<NAME>", "IT Team", "jamienewell.jpg", "<p>NOT VERY GOOD AT THIS</p>", "<EMAIL>"); teamBio("<NAME>", "Sales Team", "yusufahmed.jpg", "", "<EMAIL>"); teamBio("<NAME>", "Sales Team", "christianbaldwin.jpg", "", "<EMAIL>"); teamBio("<NAME>", "Sales Team", "dylangillespie.jpg", "", "<EMAIL>"); ?> <div class="col-xs-12 col-sm-12 col-md-6 offset-xl-0 col-xl-6"> <?php teamBio_alone("<NAME>", "Marketing Team", "samlau_new.jpg", "<p>LAUD PRAUD<br/>AND LOVES SWEET ONIONS.</p>", "<EMAIL>"); ?> </div> <div class="col-xs-12 col-sm-12 offset-md-3 col-md-6 offset-xl-0 col-xl-6"> <?php teamBio_alone("<NAME>", "Marketing Team", "katekaplya.jpg", "", "<EMAIL>"); ?> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> <script type="text/javascript" src="/js/cardHeights.min.js"></script> <script type="text/javascript" src="/js/connectivate.js"></script> </body> </html> <file_sep> $(document).ready(function(){ // Event listener for each sample project $(".portfolio-box").on("click", function(){ ExpandSampleProject(this); }); }); function ExpandSampleProject(projectContainer){ var projectWindow = $("#exampleProjectModal"); var projectWindowTitle = $(projectContainer).find(".project-category").first().text().trim(); var projectWindowImage = $(projectContainer).find("img").first().attr("src"); var projectWindowDetails = $(projectContainer).find(".project-details").first().html(); var projectWindowDescription = $(projectContainer).find(".project-description").first().html(); // Fill the modal with the correct project info $(projectWindow).find("#exampleProjectModalTitle").text(projectWindowTitle); $(projectWindow).find("#exampleProjectImage").attr("src", projectWindowImage); $(projectWindow).find("#project-window-details").html(projectWindowDetails); $(projectWindow).find("#project-window-description").html(projectWindowDescription); // Open the modal $("#exampleProjectModal").modal('show'); }<file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, SeaCandy Tackle"> <meta name="description" content="SeaCandy Tackle would like to build a new website, with clean and interesting UI. Most importantly, customers should be able to shop for products online. This is an exciting opportunity to dive into some fullstack web development!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, SeaCandy Tackle</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/seacandytackle-banner.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/seacandytackle-banner.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$680.00</h2> <h2 class="project-price-narrow hidden-md-up">$680.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">SeaCandy Tackle</p> <p class="project-descriptive-text">Project due: February 5th</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">SeaCandy Tackle would like to build a new website, with clean and interesting UI. Most importantly, customers should be able to shop for products online. This is an exciting opportunity to dive into some fullstack web development!</p> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with <NAME> to discuss website vision and specifications </li> <li> Create a website with the required information and colour scheme </li> <li> Allow users to log-in and access a shopping page in which customers can easily see prices and descriptions of items </li> <li> The site must have a simple back-end for editing, adding and removing items. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Graphic design skills an asset </li> <li> Web development </li> <li> Experience with online-order implementation </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - App Dev, E-start"> <meta name="description" content="E-start is a new venture from a current student at Queen’s Masters of Entrepreneurship and Innovation program. This company is an educational video content provider for preschool to high school age kids in Nigeria."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>e-start, app, android, design, development, video"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - App Dev, E-start</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/iphone.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/iphone.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Android App Development - Back End</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$1750 plus equity</h2> <h2 class="project-price-narrow hidden-md-up">$1750 plus equity</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">E-Start</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">E-start is a new venture from a current student at Queen’s Masters of Entrepreneurship and Innovation program. This company is an educational video content provider for preschool to high school age kids in Nigeria. People in Nigeria have little access to textbooks or ways to learn, and E-start looks to solve this problem. Most people in Nigeria have access to Android phones, and have periodic access to the internet. The project will focus on developing this Android App. </p> <p class="project-descriptive-text">Subscribers pay online from our website (or offline) and obtain a code. The code will enable the subscriber to download the app, and browse for content from a store online. Once downloaded, the content can be accessed on the subscribers’ device offline.</p> <p><strong>Timeline</strong></p> <p class="project-descriptive-text"> Estimated deliverable is end of January/ early February but flexible. <strong>You are not expected to begin working on it much until after exams.</strong> </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Back end Android app functionality </li> <li> How to work as part of a team </li> <li> Suggest ideas and help creative direction </li> </ul> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">The overall task is to create a mobile Android app, such as the Bookshelf™ software at <a href=https://www.vitalsource.com/><font>https://www.vitalsource.com/</font></a></p> <ul class="project-descriptive-text"> <li> Work with the client to flesh out the idea, and advise them technically </li> <li> Primarily responsible for the account system, video storage system, and video playback system </li> <li> Include a way to make the videos non-transferrable between devices </li> <li> Develop a fully functional and easy-to-use e-commerce shopping cart </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Back end Android app development experience is a necessity </li> <li> Project management and collaborative skills </li> <li> Experience with testing software </li> </ul> <p><strong>This project accepts applications on a rolling basis, and could be closed at any time.</strong></p> <p><strong>Send in an application for an opportunity to discuss the project more with the client!</strong></p> <p><?php echo $applicationInstructionString ?></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/greencity-urbanfarming.JPG" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/greencity-urbanfarming.JPG" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Urban Farming Capsule Re-Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$350.00</h2> <h2 class="project-price-narrow hidden-md-up">$350.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">GreenCity Initiatives</p> <p class="project-descriptive-text">Project due: January 31st</p> <br /> <p><strong><em>This project can be applied to either individually, or as a small group</em></strong></p> <p><strong>Description</strong></p> <p class="project-descriptive-text" style="opacity: 1;"> <span class="project-descriptive-text">A new urban farming system, created by Omega Garden, allows plants like herbs, lettuce, and micrograins to be grown in a capsule system. The plants are installed on the walls of the capsule and rotated around a light source</span> <img class="floating-img" src="../img/project/greencity-urbanfarming-capsules.JPG" /> <span class="project-descriptive-text">held in the center. They receive nutrients by being rotated through a ‘pool’ of nutrient-filled water a few times per hour. The result is a farming system that allows these plants to be grown indoors, and in ⅛ the usual time.</span> </p> <p class="project-descriptive-text">GreenCity Initiatives is looking to speed up the seeding process of their current Urban Farm rotary system. Currently, seeded plants are inserted individually into the walls of the capsules which takes a considerable amount of time. Either a new plant insertion system, or a new capsule system, needs to be designed to speed up the process.</p> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Meet with the client (<NAME>) to understand the current system and the project goals </li> <li> Research and design a new capsule system </li> <li> Create a thorough and precise AutoCAD model of the final design, one which can be used to manufacture a physical prototype </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> AutoCAD proficiency </li> <li> Experience with mechanical engineering design </li> <li> Problem solving, creativity, and the ability to research </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php /*This file contains functions for quickly creating project cards*/ $projectPath = '//'.$_SERVER['SERVER_NAME'].'/projects/'; $imagePath = '//'.$_SERVER['SERVER_NAME'].'/img/project/'; function openProjectCard($projectName, $projectImage, $projectPhpPage, $projectCompany, $projectDescription, $appDueString, $price) { echo "<a href=\"" . $GLOBALS['projectPath'] . $projectPhpPage . "\" class=\"project-card-link\"> <div class=\"card card-size1 card-inverse project-card\"> <img class=\"card-img-top project-card-img-top\" img src=\"" . $GLOBALS['imagePath'] . $projectImage . "\" alt=\"Card image cap\" /> <div class=\"card-block text-xs-center\"> <h3 class=\"card-title\">" . $projectName . "</h3> <h4 class=\"card-subtitle\">" . $projectCompany . ' - $' . $price . "</h4> <p class=\"card-text card-bottom-text-underneath\">" . $projectDescription . "</p> <p class=\"card-bottom-text\">$appDueString</p> </div> </div> </a>"; } function closedProjectCard($projectName, $projectImage, $projectPhpPage, $projectCompany) { echo "<div class=\"col-md-6 col-lg-4 col-sm-10 col-xs-8 offset-md-0 offset-sm-1 offset-xs-2\"> <a href=\"" . $GLOBALS['projectPath'] . $projectPhpPage . "\" class=\"project-card-link\"> <div class=\"card closed-card card-inverse \" style=\"background-image : url(" . $GLOBALS['imagePath'] . $projectImage . "); background-size: 500px auto;\"> <div class=\"closed-project-card-overlay\"> <h3 class=\"closed-stamp-text\">Closed</h3> <h3 class=\"card-title\">" . $projectName . "</h3> <h5 class=\"card-subtitle\">" . $projectCompany . "</h5> </div> </div> </a> </div>"; } ?><file_sep> (function($) { "use strict"; // Start of use strict $("h1.connectivate").fitText( 1.2, { minFontSize: '35px', maxFontSize: '85px' }); $("#phonetics").fitText( 1.8,{ minFontSize: '20px', maxFontSize: '40px' }); })(jQuery); // End of use strict <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/solarpanels.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/solarpanels.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Business Efficiency Consultation</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$100.00</h2> <h2 class="project-price-narrow hidden-md-up">$100.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">CDK Walk In Clinic</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">CDK would like to maximize the efficiency of its business and daily operations. To accomplish this, changes to their current operations, IT systems, patient organization and other aspects may need to occur. In order to make these changes, CDK requires someone to research into the company's current business operations to find sources of lost efficiency. This is an opportunity to acquire an in-depth understanding of business operations, and to creatively problem solve an open-ended challenge.</p> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">Consult for CDK by doing the following:</p> <ol class="project-descriptive-text"> <li> Meeting with members of the CDK team </li> <li> Observing the operations of the company in person </li> <li> Conducting internal and external research </li> </ol> <p class="project-descriptive-text">Draft a report outlining areas of inefficiency, with recommendations for improvement along with a plan for implementation.</p> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Business consulting experience </li> <li> Comfortable analyzing company operations and asking in-depth questions to various employees </li> <li> Strong research, analysis, report-writing and other soft skills </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/beerflight.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/beerflight.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Brand Ambassadors</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$225</h2> <h2 class="project-price-narrow hidden-md-up">$225</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Gananoque Brewing Company</p> <br /> <p><strong><em>This Project Has 6+ Positions Available</em></strong></p> <p><strong>Description</strong></p> <p class="project-descriptive-text"> Gananoque Brewing Company (GBC) is a micro-brewery brewing tasty beers in the Kingston area (Gananoque). They sell craft beer to bars and restaurants in Eastern Ontario and operate a beer home delivery service in Kingston. </p> <p class="project-descriptive-text">They need brand ambassadors to sell their beer home delivery service using existing relationships, social media, and affinity groups (organizations, clubs, sports teams). Let's rephrase that. An amazing beer company wants you to tell your friends about them, and they'll pay you for it. Awesome. </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Master sales strategies and tactics </li> <li> Acquire a greater appreciation for craft beer </li> </ul> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Meet with GBC to discuss their beer and their home delivery service. </li> <li> Sell kegs through the GBC home delivery service to your contacts. </li> <li> The goal for each ambassador is to sell 10 kegs. </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Self-starter, outgoing, personable, motivated by results </li> <li> Must meet requirements of the Alcohol and Gaming Commission (19+, no criminal record, etc) </li> <li> Must be keen to represent Kingston area's best microbrewery! </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/coins.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/coins.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Sales Project</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$150.00</h2> <h2 class="project-price-narrow hidden-md-up">$150.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">CDK Walk In Clinic</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">CDK is looking to add a revenue stream by selling advertisement space on its TV. The TV is watched by hundreds of patrons every day and could be a great source of advertising for local businesses.</p> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">Estimate and consult with <NAME> to determine advertisement rates. Canvass local businesses and make sales of advertising space. If necessary, design the advertisements for those businesses. Successful completion of this project depends on making at least one sale of advertising space.</p> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Sales experience </li> <li> Marketing experience </li> <li> Graphic design an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Design, Facio Co."> <meta name="description" content="Facio Corporation recognizes the need for their current website to be given a more modern look and to have its content updated. This is an opportunity to take on a design consultant role to plan a solution that fits Facio's needs, and to actually implement it and have it published!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,facio,facio corporation"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Design, Facio Co.</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/1000islandsoap-webdev.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/faciocorporation-small.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Design</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$300.00</h2> <h2 class="project-price-narrow hidden-md-up">$300.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Facio Corporation</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Facio Corporation recognizes the need for their current website (<a href="http://www.facio.ca/">facio.ca</a>) to be given a more modern look and to have its content updated. This is an opportunity to take on a design consultant role to plan a solution that fits Facio's needs, and to actually implement it and have it published!</p> <p><strong>Responsibilities</strong></p> <ul class="project-descriptive-text"> <li> Discuss options for the layout of the website with the Operations Manager (<NAME>), and decide upon a new, modern layout. </li> <li> Use text and image content provided by <NAME>, and update all sections of the site with the new content and fresh layout. </li> <li> Potentially add some photographs of past projects, and limited interactivity. </li> </ul> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Website development knowledge, including javascript </li> <li> Motivation </li> <li> Ability to manage deadlines </li> <li> Prior experience in web development is an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, Dharani Healing Arts"> <meta name="description" content="Dharani Healing Arts, a holisitic health practice offering organic herbal teas, is looking for a student to revamp their website."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,dharani, healing, arts, andrée, beauchamp, web, design, development"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, Dharani Healing Arts</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/laptop.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/laptop.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$300.00</h2> <h2 class="project-price-narrow hidden-md-up">$300.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Dharani Healing Arts</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text"><NAME> is a holistic health practitioner and therapeutic herbalist who also offers a line of organic herbal teas. To better serve people looking to improve their health through her practice, she would like her website revamped!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Create a professional website </li> <li> Learn about e-commerce platforms for selling goods online </li> <li> Discover holistic health practices for improving your health! </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Update site to accomodate mobile users </li> <li> Revise fonts and look of site for a better user experience </li> <li> Set up registration and purchases through paypal for courses </li> <li> Improve user engagement </li> <li> Add move to shop/move items </li> <li> Set up calendar properly </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Knowledge of wordpress and paypal integration </li> <li> Experience with web design and development </li> <li> Creativity and motivation </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/security.php' ?> <section id="contact"> <div class=" text-xs-center"> <h2 class="section-heading">Contact Us</h2> <hr class="primary" /> </div> <div class="container"> <div class="row"> <div class="text-xs-center col-md-12"> <h4 style="margin:20px 0px 30px 0px"> Want to learn more? Have questions about our process?<br /><br /> We'd love to hear from you.<br /> </h4> </div> </div> <div class="row"> <div class="col-md-4 text-xs-center" style="align-content:center; margin-bottom:20px"> <a href="https://www.facebook.com/connectiv8"> <i class="fa fa-facebook-official fa-3x wow bounceIn" data-wow-delay=".1s"></i> </a> </div> <div class="col-md-4" style="align-content:center"> <a href="mailto:<EMAIL>" style="margin:auto;"> <div class="text-xs-center"> <i class="fa fa-envelope-o fa-3x wow bounceIn" data-wow-delay=".1s"></i> <p> <EMAIL> </p> </div> </a> </div> <div class="col-md-4 text-xs-center" style="align-content:center"> <a href="https://www.linkedin.com/company/10227642" style="margin:auto;"> <i class="fa fa-linkedin-square fa-3x wow bounceIn" data-wow-delay=".1s"></i> </a> </div> </div> </div> </section> <footer> <p class="small">&copy; Connectivate Corp. 2016</p> <img src="//<?php echo $_SERVER['SERVER_NAME'].'/img/Logos/C8_Logo_version_1.2.png'?>" style="margin:0px 0px 30px 0px" height="25" /> </footer> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/business.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/business.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Marketing Project</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$100.00</h2> <h2 class="project-price-narrow hidden-md-up">$100.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Graham's Pharmacy</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Graham's Pharmacy would like to improve the marketing and outreach of its products to different demographics in the Kingston area. This is your chance to get involved with a real business, and to plan a marketing campaign that can actually be put into effect! Particular focus should be given to the following demographics: Queen's, Downtown Kingston and Wolfe Island.</p> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">Students should both generate new marketing initiatives, and develop ways to improve the current initiatives. The final deliverable will be in the form of a report to <NAME>, the owner, and should assess the costs, feasibility and value-added of each of the ideas. You are expected to give an overview of all ideas investigated, and recommend the best ones to implement. </p> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Marketing experience </li> <li> Effective communication and report-writing skills </li> <li> Ability to conduct thorough research to determine effective outreach initiatives </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/barbershop.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/barbershop.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Social Media Management</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$200.00</h2> <h2 class="project-price-narrow hidden-md-up">$200.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Generations Barbershop</p> <p class="project-descriptive-text">Project due: February 28th</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Generations Barbershop is looking to expand their presence online with a new social media account manager. This is a rare opportunity to acquire a return on all the time you spend on Facebook and Instagram. Go online and use some creative humour and design to get people talking about Generations Barbershop, all while making money!</p> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">Manage Generations Barbershop’s Facebook and Twitter for 2 months and explore the feasibility of new social opportunities such as Instagram, Yelp etc. Increase Facebook page likes to 200 (currently 81) and promote Generations to Queens' social community. Meet with <NAME> to understand his social media goals.</p> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Social media proficiency </li> <li> Promotional and advertising experience a plus </li> <li> Graphic design an asset </li> </ul> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Frosh Week & Events Coordinator, Drugsmart Pharmacy"> <meta name="description" content="Drugsmart Pharmacy wants to make the most of the new semester excitement by having coordinated marketing events around Frosh week, the sidewalk sale, and beyond. Help it out!"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,Drugsmart Pharmacy, marketing, events coordinator, frosh week"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Frosh Week & Events Coordinator, Drugsmart Pharmacy</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/coins.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/coins.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Frosh Week & Events Coordinator</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$1270.00</h2> <h2 class="project-price-narrow hidden-md-up">$1270.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">DrugSmart Pharmacy</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">The DrugSmart Pharmacy in the Queen's ARC needs a student to coordinate frosh week promotion and other marketing events for the drug store. Events could include a presence at the Sidewalk Sale, makeup demonstrations, coupon giveaway blitzes, and focus groups. The goal is to promote awareness of and goodwill towards DrugSmart. The student will also be expected to come up with their own ideas, so have some fun with it!</p> <p class="project-descriptive-text">This is a big project, which will require preparatory work in July and August, with work tapering off into the school year. It is ideal if the student is in Kingston for the summer, though not required. The student <em>must</em> be available in Kingston for all of Frosh week (September 4th onwards). The position concludes in March, and the project fee will be split into several payments.</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Practice project management skills, balancing objectives against deadlines and budget constraints. </li> <li> Learn to evaluate and then execute marketing ideas. </li> <li> Gain insight into a functioning pharmacy, and network with a pharmacy owner with connections in the industry. </li> <li> Work in a team with other brand ambassadors during frosh week and beyond. </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Meet with Suzanne from DrugSmart Pharmacy, and discuss marketing objectives. </li> <li> Over July and August, plan your frosh week and early semester marketing events. </li> <li> Once September hits, execute those plans! </li> <li> Evaluate your completed events, and plan more events based on this analysis. </li> <li> Most work will be done in July and August, with work dropping to a few hours a week after September, and no need to work during exams. The project wraps up in March, 2017. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Organization </li> <li> Affiliation with various Queen's groups and/or connections with diverse areas of the student body. </li> <li> Knowledge of advertising opportunities on campus, including poster approval requirements, etc. </li> <li> The ability to manage and motivate others. </li> </ul> <p><strong>Applications are now closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Development, Cozii.co"> <meta name="description" content="Cozii.co is a new venture aiming to deliver a unique customer service from local, fully-vetted home service providers using both web and mobile platforms. Cozii.co will feature search, discover, private instant messaging, reviews and referencing, social network integration, image attachments, and a global payment system. This start-up is offering an amazing paid + equity opportunity to develop the first prototype for this platform."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>,web development,backend,frontend,back-end,front-end,cozii.co,cozii"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Development, Cozii.co</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/laptop-coffee.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/laptop-coffee.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web and App Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$1000+ and Equity</h2> <h2 class="project-price-narrow hidden-md-up">$1000+ and Equity</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Cozii.co</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Cozii.co is a new venture aiming to deliver a two-sided marketplace platform - web and mobile - to book/request home maintenance services in real-time. Two students are needed for this project: one to focus on the website and the other to focus on the mobile app. The two students will get to collaborate to make sure that the functions of both platforms are well integrated. Note that you can apply as a team! </p> <p class="project-descriptive-text">This start-up is offering an amazing paid and equity opportunity to develop <b>a minimum viable platform (product)</b>! The exact split will be determined by you and the founder if you are chosen for this project. The founder is expecting the work to be heavily concentrated between January and February 2017. </p> <p class="project-descriptive-text">Send in your resum&eacute; if you're interested in discussing this project further!</p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Learn to work directly with an entrepreneur </li> <li> Create an amazing developer portfolio to show future employers </li> <li> Gain insight into launching a start-up, working directly with a member of the Queen's Masters of Entrepreneurship and Innovation program </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Assist with developing a database system to serve both the web and mobile apps. </li> <li> Meet with the client once a week. </li> <li> Demo the functional site and mobile app to the client, and make updates as needed. </li> <li> Deliver a highly functional website and mobile app at the end of the project. </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> The ability to convert a broad concept into a highly functional product. </li> <li> Knowledge of client side and server-side development i.e. MySQL, PHP and Apache <li> Knowledge of front-end development i.e. HTML, CSS, JavaScript and Ajax <li> Knowledge of mobile-app development for iOS and Android </li> </ul> <p><strong>This project accepts applications on a rolling basis, and could be closed at any time.</strong></p> <p><strong>Applications can also be sent in as a team.</strong></p> <p><?php echo $applicationInstructionString ?></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectivate</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/grahamspharmacy-retirementmarketing.jpg" /> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/grahamspharmacy-retirementmarketing.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Retirement Home Sales and Marketing</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$100.00 + bonus</h2> <h2 class="project-price-narrow hidden-md-up">$100.00 + bonus</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Graham's Pharmacy</p> <p class="project-descriptive-text">Project Ongoing</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">Help Graham’s Pharmacy expand its client base to retirement home service providers, now available to small pharmacy drug providers due to a legislation change. <NAME> is looking for a social, business-minded student with strong sales skills to meet with retirement home service providers and sell Graham’s pharmacy as their pharmaceutical drug provider of choice.</p> <p><strong>Responsibilities</strong></p> <p class="project-descriptive-text">Meet with <NAME> to clarify the objectives and discuss your approach. Speak to administrators of retirement home service providers to sell Graham's Pharmacy as their pharmaceutical provider, and provide them with fresh promotional material. Create a concise report on results of contacts and successful sales. </p> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Experience in marketing and making sales </li> <li> Be able to interact with residents and staff and make them feel comfortable </li> <li> Experience in creating marketing materials and handouts </li> </ul> <p><strong>The Bonus</strong></p> <p class="project-descriptive-text">This project also has an associated bonus with it. You will recieve $1000 for getting a retirement home to agree to give Graham's Pharmacy exclusive access and $500 for making a sale to a single resident and allowing Graham's Pharmacy Marketing Access to the retirement home. </p> <p><strong>Applications are closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Students"> <meta name="description" content="Acquire practical job experience working with real local businesses."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Students</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <header class="students"> <div class="header-content"> <div class="header-content-inner"> <h1>Connecting Students with Businesses</h1> <hr> <p style="color: white;">Escape the student bubble and expand your horizons.</p> <a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a> </div> </div> </header> <section class="bg-primary with-shadow" id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2 text-xs-center"> <h2 class="section-heading">Step up your game</h2> <hr class="light"> <p class="text-faded">If you want more than a theoretical education, if you want to put your skills and knowledge to the test, or if you want to build connections with local businesses, then Connectiv8 is what you’ve been waiting for. Connectiv8 not only gives you the opportunity to further develop your current skillset, but also enables you to earn money while you do it. We are here to put you in touch with businesses, entrepreneurs, and not-for-profits who are ready to partner with students on short-term, freelance-style projects.</p> <h3>Projects are available now!</h3> <br/> <a href="projects.php" class="btn btn-default btn-xl">Projects</a> </div> </div> </div> </section> <section id="process"> <div class="container"> <div class="row"> <div class="col-lg-12 text-xs-center"> <h2 class="section-heading">The Process</h2> <hr class="primary"> </div> </div> </div> <div class="container"> <div class="row"> <div class="student-process-box col-md-6 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-search wow bounceIn text-primary" data-wow-delay=".1s"></i> <h3>1) Find</h3> <p class="text-muted">What interests you? What skills do you want to develop? We endeavour to collect projects from all disciplines and all industries, so look around. If we don’t have something you’re interested in, let us know and we’ll see what we can do!</p> </div> </div> <div class="student-process-box col-md-6 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-pencil-square-o wow bounceIn text-primary"></i> <h3>2) Apply</h3> <p class="text-muted">Sign up with Connectiv8 and let us know your interests and your experience with our general application. Potential employers will use this information to get to know you and, hopefully, pick you for their project, so think carefully!</p> </div> </div> <div class="student-process-box col-md-6 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-envelope wow bounceIn text-primary" data-wow-delay=".2s"></i> <h3>3) Connect</h3> <p class="text-muted">If your enthusiasm and skills knock a business's socks off, we’ll get in touch to work out the details.</p> </div> </div> <div class="student-process-box col-md-6 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-magic wow bounceIn text-primary" data-wow-delay=".3s"></i> <h3>4) Create</h3> <p class="text-muted">Show off your skills developing your project for your client, and challenge yourself to expand your skillset as you go.</p> </div> </div> <div class="student-process-box col-md-12 text-xs-center"> <div class="service-box"> <i class="fa fa-4x fa-money wow bounceIn text-primary" data-wow-delay=".3s"></i> <h3>5) Collect</h3> <p class="text-muted">You’ll sign a contract with your client before you start working. When you’re done, celebrate!</p> </div> </div> </div> </div> </section> <section id="email" class="bg-dark with-shadow"> <div class="container text-xs-center"> <div class="call-to-action"> <h2>Want to keep in touch?</h2> <p>Click the following link to register for our mailing list! We'll notify you whenever we post new projects.<br/> Don’t worry, you can unsubscribe at any time.</p> <a id="register-link" href="http://connectiv8.us12.list-manage1.com/subscribe?u=971315d21c53efd0f3cbb5403&id=312b6aedcc" class="btn btn-default btn-xl">Register</a> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> <script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/signup-forms/popup/embed.js" data-dojo-config="usePlainJson: true"></script> <script type="text/javascript" src="/js/cookies.min.js"></script> <script type="text/javascript" src="/js/registerInit.min.js"></script> </body> </html><file_sep># Connectivate-Info This repo is meant for building the Connectivate marketing/information website. This is a simple static website, with no database connections necessary. It should look pretty though! Let's get to it! <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php'; ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectCardGenerator.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="cache-control" content="public, max-age=1200"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8"> <meta name="description" content="Connectiv8 provides a platform for students and businesses to collaborate through paid projects. Extend your learning outside the classroom."> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>"> <meta property="og:site_name" content="Connectiv8"/> <meta property="og:title" content="Home"/> <meta description="og:description" content="Connectiv8 provides a platform for students and businesses to collaborate through paid projects. Extend your learning outside the classroom."/> <meta property="og:image" content="//connectiv8.com/img/Logos/C8_Logo_version_1.2.png" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://connectiv8.com" /> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <header id="top" class="main"> <div class="header-content"> <div class="header-content-inner"> <!--<h1 class="connectivate">connectivate</h1>--> <img id="main-header-logo" src="/img/Logos/Connectiv8_Web_PNG_version_1.2.png"> <h3 id="phonetics">(kuh-<b>nekt</b>-i-veyt)</h3> <hr/> <a href="#projects" class="btn btn-primary btn-xl btn-cn page-scroll">View Projects</a> <a href="#about" class="btn btn-primary btn-xl btn-cn page-scroll">Find Out More</a> </div> </div> <p class="header-subtitle-low">Take your education outside the classroom by solving a problem for a local business.</p> </header> <section id="projects"> <div class="container"> <div class="text-xs-center"> <h2 class="">Projects</h2> <h3>Projects are open again for the new school year!</h3> <h3>Check them out, alongside our previous projects, on the <a href="projects.php">Projects</a> page.</h3> </div> </div> </section> <section class="bg-primary with-shadow" id="about"> <div class="container"> <div class="row"> <div class="col-lg-8 offset-lg-2 text-xs-center"> <h2 class="section-heading">About Connectiv8</h2> <hr class="light"> <p class="text-faded">Connectiv8 provides a platform for students and businesses to collaborate. It solves a universal problem - bridging the gap between school and employment. Connectiv8 facilitates a partnership between students and businesses, where projects are shared between the two. Students’ passion and energy are exactly what businesses and not-for-profits need to solve problems with fresh ideas. By passing their projects off to talented students, they are also providing valuable learning opportunities and fuel for skill development for motivated students.</p> <h3> Let's get started. </h3> <a href="businesses.php" class="btn btn-default btn-xl btn-cn">I'm a business</a> <a href="students.php" class="btn btn-default btn-xl btn-cn">I'm a student</a> </div> </div> </div> </section> <section id="partners" style="padding-top:40px; padding-bottom: 0px;"> <div class=" text-xs-center"> <h2 class="section-heading" style="font-size: 40px">Partners</h2> </div> </br> <div class="container"> <div class="row"> <div class="text-xs-center col-md-4 offset-md-4 col-xs-12 offset-0"> <img class="partner" src="/img/partners/BMO.JPG"> </div> </div> </div> <hr style="max-width: 4000px; border-width: 1px; border-color: #cccccc; margin-top: 50px; margin-bottom: 0px; margin-left: 50px; margin-right: 50px; text-align: center;"/> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> <script type="text/javascript" src="/js/cardHeights.min.js"></script> <script type="text/javascript" src="/js/connectivate.js"></script> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php' ?> <?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/projectPageGenerator.php' ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="title" content="Connectiv8 - Web Dev, Pivot"> <meta name="description" content="Pivot, The site will showcase events and information from across industries and across the country"> <meta name="keywords" content="<?php echoGeneralKeywords(); ?>pivot, web, design, development, news"> <meta name="author" content="Connectivate Corporation"> <!-- favicon/icon import --> <?php favicons(); ?> <title>Connectiv8 - Web Dev, Pivot</title> <!-- CSS import --> <?php css(); ?> </head> <body id="page-top"> <!-- Google Tag Manager --> <?php analytics(); ?> <!-- Navbar --> <?php navbar(); ?> <section style="padding-bottom: 0px;" class="bg-dark with-shadow" id="project"> <div style="height: 100%;" class="container-fluid"> <div style="height: 100%;" class="row"> <div id="image-column" style="padding: 0px; height: 100%; overflow-x: hidden;" class="col-md-4"> <div style="text-align:center; height: 100%; overflow-x: hidden;"> <img class="project-image-wide hidden-sm-down" src="../img/project/webdesign.jpg" alt="Project Picture"/> <!--project picture--> </div> <div> <img class="img-responsive hidden-md-up" src="../img/project/webdesign.jpg" alt="Project Picture" /> <!--project picture--> </div> </div> <div id="description-column" class="col-md-8"> <div style="margin: 20px;"> <!-- Project Header --> <div class="container" style="padding-left: 0px; padding-right: 0px; margin-left:0px"> <div class="row"> <h2 class="col-md-8 project-title">Web Development</h2> <div class="col-md-4"> <h2 class="project-price-wide hidden-sm-down">$375.00</h2> <h2 class="project-price-narrow hidden-md-up">$375.00</h2> </div> </div> </div> <p class="project-descriptive-text" style="margin-bottom: 5px;">Pivot</p> <br /> <p><strong>Description</strong></p> <p class="project-descriptive-text">This will be a content platform developed using Squarespace for specific industry-related news. The site will showcase events and information from across industries and across the country. Revenue streams will be traditional advertising, sponsored posts, and sponsored content. This project will give the student great web design experience with a Masters of Entrepreneur & Innovation student working on an exciting startup.</p> <p><strong>Timeline</strong></p> <p class="project-descriptive-text"> Estimated deliverable will be sometime in the winter term but is flexible. <strong>You are not expected to begin working on it much until after exams.</strong> </p> <p><strong>Learning Opportunities</strong></p> <ul class="project-descriptive-text"> <li> Web design in squarespace </li> <li> How to structure large chunks of information </li> <li> How to work as part of a team </li> <li> Suggest ideas and help creative direction </li> </ul> <p><strong>Responsibilities</strong></p> <ol class="project-descriptive-text"> <li> Create an online news platform using Squarespace catering to sharing information </li> <li> Platform will allow for displaying news, have a header with multiple sections, and have the ability to archive information </li> </ol> <p><strong>Required Skills</strong></p> <ul class="project-descriptive-text"> <li> Loves problem solving and is excited to build this type of platform </li> <li> Knowledgeable in UI/UX design </li> <li> Flexible to work through iterations and ideas </li> <li> Recommend best practices but not be strict about holding them </li> </ul> <p><strong>Applications are now closed for this project.</strong></p> </div> </div> </div> </div> </section> <!-- Contact us and copyright --> <?php footer(); ?> <!-- JS --> <?php js(); ?> </body> </html> <file_sep><?php include_once $_SERVER['DOCUMENT_ROOT'].'/functions/security.php' ?> <?php $page = $_SERVER['PHP_SELF']; ?> <nav class="navbar navbar-light bg-faded navbar-fixed-top with-shadow"> <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar2"> &#9776; </button> <div class="collapse navbar-toggleable-sm" id="exCollapsingNavbar2"> <!-- Small landscape logo should go here --> <a class="navbar-brand page-scroll" href="/index.php#top" style="margin:4px 4px 0px 0px"> <img src="//<?php echo $_SERVER['SERVER_NAME'].'/img/Logos/C8_Logo_version_1.2.png'?>" height="25"></img> </a> <ul class="nav navbar-right pull-md-left text-sm-right"> <li class="nav-link"> <a href="//<?php echo $_SERVER['SERVER_NAME']?>/businesses.php#top" style="margin-bottom:1px;" class="card-link btn btn-primary page-scroll <?php if ($page == "/businesses.php") { echo "active";} ?>" >Businesses</a> </li> <li class="nav-link"> <a href="//<?php echo $_SERVER['SERVER_NAME']?>/students.php#top" style="margin-bottom:1px;" class="card-link btn btn-primary page-scroll <?php if ($page == "/students.php") { echo "active";} ?>" >Students</a> </li> </ul> <!-- Collect the nav links, forms, and other content for toggling --> <ul class="nav navbar-right text-xs-right float-lg-right"> <li class="nav-link"> <a href="//<?php echo $_SERVER['SERVER_NAME']?>/projects.php#top" class="card-link btn btn-primary page-scroll">Projects</a> </li> <li class="nav-link dropdown"> <a class="card-link btn btn-primary page-scroll dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> About </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a href="#" class="dropdown-item page-scroll">How it Works</a> <a href="#" class="dropdown-item page-scroll">Our Story</a> <a href="//<?php echo $_SERVER['SERVER_NAME']?>/team.php#top" class="dropdown-item page-scroll">Team</a> <a href="#contact" class="dropdown-item page-scroll">Contact Us</a> </div> </li> <li class="nav-link"> <a class="card-link btn btn-primary page-scroll" href="#contact"> Contact Us <i class="fa fa-envelope-o wow bounceIn" data-wow-delay=".1s"></i> </a> </li> </ul> </div> </nav>
b92866d219c5beb44591245f999d049156c92b7e
[ "JavaScript", "Markdown", "PHP" ]
49
PHP
alexanderkuznetsov96/Connectivate-Info
ef748facfab2c5ebdf93a231ff9210d9efb3c09a
edcff854417978705951e0edaebebc93aee95040
refs/heads/master
<repo_name>rabbitfighter81/learnyounode-coffee<file_sep>/generated-JS/ex12-http-uppercaser.js // Generated by CoffeeScript 1.8.0 /* * HTTP UPPERCASERER: Wite an HTTP server that receives only POST requests * and converts incoming POST body characters to upper-case and returns it * to the client. * * Your server should listen on the port provided by the first argument * to your program. * * Author: <NAME> (@rabbitfighter81) */ (function() { var http, map, port, usageError; http = require("http"); map = require("through2-map"); usageError = "Usage: node ex12-http-uppercaser.js <port>"; if (process.argv.length === 3) { port = Number(process.argv[2]); http.createServer(function(request, response) { if (request.method !== "POST") { return response.end("send me a POST\n"); } request.pipe(map(function(chunk) { return chunk.toString().toUpperCase(); })).pipe(response); }).listen(port); } else { console.error(usgaeError); } }).call(this); <file_sep>/generated-JS/ex10-time-server-alternate.js // Generated by CoffeeScript 1.8.0 (function() { var net, now, port, server, usrageError, zeroFill; net = require("net"); usrageError = "Usage: node ex10-time-server-alternate.js <port>"; if (process.argv.length === 3) { port = Number(process.argv[2]); zeroFill = function(i) { return (i < 10 ? "0" : "") + i; }; now = function() { var d; d = new Date(); return d.getFullYear() + "-" + zeroFill(d.getMonth() + 1) + "-" + zeroFill(d.getDate()) + " " + zeroFill(d.getHours()) + ":" + zeroFill(d.getMinutes()); }; server = net.createServer(function(socket) { socket.end(now() + "\n"); }); server.listen(port); } else { console.error(usageError); } }).call(this); <file_sep>/generated-JS/ex06-make-it-modular.js // Generated by CoffeeScript 1.8.0 /* * MAKE IT MODULAR: Create a program that prints a list of files in a given * directory, filtered by the extension of the files. You will be provided a * directory name as the first argument to your program (e.g. '/path/to/dir/') * and a file extension to filter by as the second argument. * * For example, if you get 'txt' as the second argument then you will need * to filter the list to only files that end with .txt. Note that the second * argument will not come prefixed with a '.'. * * The list of files should be printed to the console, one file per line. * You must use asynchronous I/O. * * Author @rabbitfighter81 */ (function() { var dir, ext, filtered; filtered = require("./module.js"); if (process.argv.length === 4) { dir = process.argv[2]; ext = process.argv[3]; filtered(dir, ext, function(err, list) { if (err) { return console.error("There was an error:", err); } list.forEach(function(file) { return console.log(file); }); }); } else { console.log("Usage: node modular.js <path> <extension>"); } }).call(this); <file_sep>/generated-JS/ex04-my-first-asyncIO.js // Generated by CoffeeScript 1.8.0 /* * MY FIRST ASYNC I/O!: Write a program that uses a single asynchronous * filesystem operation to read a file and print the number of newlines it * contains to the console (stdout), similar to running * cat file | wc -l. * * The full path to the file to read will be provided as the first * command-line argument. * * Author: <NAME> (@rabbitfighter81) */ (function() { var file, fs, usageError; fs = require("fs"); usageError = "Usage: node ex4-myfirst-asyncIO.js <path-to-file>.txt"; if (process.argv.length === !3) { console.log(usageError); } else { file = String(process.argv[2]); fs.readFile(file, function(err, contents) { var lines; lines = String(contents).split("\n").length - 1; return console.log(lines); }); } }).call(this); <file_sep>/generated-JS/module.js // Generated by CoffeeScript 1.8.0 /* * A module that exports a single function that takes three arguments. * 1) The directory name * 2) The filename extension * 3) A callback function * * The callback function must be called using the idiomatic node(err, data) * convention. This convention stipulates that unless there's an error, * the first argument passed to the callback will be null, and the second will * be your data. In this case, the data will be your filtered list of files, * as an Array. If you receive an error, e.g. from your call to fs.readdir(), * the callback must be called with the error, and only the error, as the * first argument. * * Author: <NAME> (@rabbitfighter81) */ (function() { var fs, path; fs = require("fs"); path = require("path"); module.exports = function(dir, ext, callback) { fs.readdir(dir, function(err, list) { if (err) { return callback(err); } list = list.filter(function(file) { return path.extname(file) === "." + ext; }); callback(null, list); }); }; }).call(this); <file_sep>/generated-JS/ex03-synchronousIO.js // Generated by CoffeeScript 1.8.0 /* * MY FIRST I/O!: Write a program that uses a single synchronous filesystem * operation to read a file and print the number of newlines it contains to * the console (stdout), similar to running cat file | wc -l. * * The full path to the file to read will be provided as the first command-line * argument. * * Author: <NAME> (@rabbitfighter81) */ (function() { var file, filename, fs, stringsArray, usageError; fs = require("fs"); usageError = "Usage: 'node synchronous.js <path-to-file>.txt'"; if (process.argv.length !== 3) { return console.log(usageError); } filename = process.argv[2]; file = fs.readFileSync(filename); stringsArray = file.toString().split("\n"); console.log(stringsArray.length - 1); }).call(this); <file_sep>/generated-JS/ex11-http-file-server.js // Generated by CoffeeScript 1.8.0 /* * HTTP FILE SERVER: Write an HTTP server that serves the same text file for each * request it receives. * * Your server should listen on the port provided by the first argument to your * program. * * You will be provided with the location of the file to serve as the second * command-line argument. You must use the fs.createReadStream() method to stream * the file contents to the response. * * Author: <NAME> (@rabbitfighter81) */ (function() { var file, fs, http, port, usageError; http = require("http"); fs = require("fs"); usageError = "Usage: node ex11-http-file-server.js <port>"; if (process.argv.length === 4) { port = process.argv[2]; file = process.argv[3]; http.createServer(function(req, res) { res.writeHead(200, { "content-type": "text/plain" }); fs.createReadStream(file).pipe(res); }).listen(port); } else { console.error(usageError); } }).call(this); <file_sep>/generated-JS/ex10-time-server.js // Generated by CoffeeScript 1.8.0 /* * TIME SERVER: Write a TCP time server! * * Your server should listen to TCP connections on the port provided by the * first argument to your program. For each connection you must write the * current date & 24 hour time in the format: * * "YYYY-MM-DD hh:mm" * * followed by a newline character. Month, day, hour and minute must be * zero-filled to 2 integers. For example: * * "2013-07-06 17:42" * * Author: <NAME> (@rabitfighter81) */ (function() { var net, port, strftime; if (process.argv.length === !3) { return console.error("Usage: node ex10-time-server.js <port>"); } else { net = require("net"); strftime = require("strftime"); port = process.argv[2]; net.createServer(function(socket) { var date; date = new Date(); socket.end(strftime("%F %T", date).slice(0, -3)); }).listen(port); } }).call(this); <file_sep>/generated-JS/ex01-hello-world.js // Generated by CoffeeScript 1.8.0 /* * HELLO WORLD: Write a program that prints the text "HELLO WORLD" to the * console (stdout) * * Author: <NAME> (@rabbitfighter81) */ (function() { if (process.argv.length === 2) { console.log("HELLO WORLD"); } else { console.error("Usage: node ex1-hello-world.js"); } }).call(this); <file_sep>/README.md # learnyounode-coffee CoffeeScript solutions to NodeSchool.io's "learnyounode" tutorials. Also contains JavaScript solutions Generated by CoffeeScript 1.8.0 # Usage To use these files with learnyounode, you must 1) have node installed, and 2) have CoffeeScript installed, and 3) have learnyounode installed. <ul> <li>To install coffeescript: <code>npm install -g coffee-script</code></li> <li>To install learnyounode: <code>npm install -g learnyounode</code></li> </ul> To compile the coffee files to js, run <code>coffee -c file.coffee</code> and then verify them using <code>learnyounode verify file.js</code> You could also run them without learnyounode, just with coffee using <code>coffee file.coffee</code> if you know the parameters to use, or you could add <code>#!/usr/bin/env coffee</code> to the header, make the script executable using <code>chmod +x file.coffee</code> and run it like any other script. # Author <NAME> (@rabbitfighter81) # Licence MIT <file_sep>/generated-JS/ex05-filtered-list.js // Generated by CoffeeScript 1.8.0 /* * FILTERED LS: Create a program that prints a list of files in a given * directory, filtered by the extension of the files. You will be provided a * directory name as the first argument to your program (e.g. '/path/to/dir/') * and a file extension to filter by as the second argument. * * For example, if you get 'txt' as the second argument then you will need to * filter the list to only files that end with .txt. Note that the second * argument will not come prefixed with a '.'. * * The list of files should be printed to the console, one file per line. * You must use asynchronous I/O. * * Author: <NAME> (@rabbitfighter81) */ (function() { var directory, extension, fs, path, usageError; fs = require("fs"); path = require("path"); usageError = "Usage: ex5-filtered-list.coffee <directory> <extension>"; if (process.argv.length === 4) { directory = process.argv[2]; extension = "." + process.argv[3]; fs.readdir(directory, function(err, list) { if (err) { console.error(err); } return list.forEach(function(file) { if (path.extname(file) === extension) { return console.log(file); } }); }); } else { console.error(usageError); } }).call(this);
ff06e0e4df3e9fb306638c15c664d1489717b845
[ "JavaScript", "Markdown" ]
11
JavaScript
rabbitfighter81/learnyounode-coffee
50828100b30a6c488e0480d93b81d68ee0948108
6bfd9bbecd0fe652966f4e386622885fd18179b7
refs/heads/master
<repo_name>HungryZ/HungryTools<file_sep>/HungryTools/Classes/Category/UIView+Frame.swift // // UIView+Frame.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UIView { var top: CGFloat { get { frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } var left: CGFloat { get { frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } var bottom: CGFloat { get { frame.origin.y + frame.size.height } set { var frame = self.frame frame.origin.y = newValue - self.frame.size.height self.frame = frame } } var right: CGFloat { get { frame.origin.x + frame.size.width } set { var frame = self.frame frame.origin.x = newValue - self.frame.size.width self.frame = frame } } var centerX: CGFloat { get { center.x } set { center = CGPoint(x: newValue, y: center.y) } } var centerY: CGFloat { get { center.y } set { center = CGPoint(x: center.x, y: newValue) } } var width: CGFloat { get { frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } var height: CGFloat { get { frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } } <file_sep>/HungryTools/Classes/Category/UILabel+Init.swift // // UILabel+Init.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UILabel { convenience init(font: Any = 14, textColor: UIColor? = nil, text: String? = nil) { self.init() if font is Int { self.font = .systemFont(ofSize: CGFloat(font as! Int)) } else if font is Double { self.font = .systemFont(ofSize: CGFloat(font as! Double)) } else if font is CGFloat { self.font = .systemFont(ofSize: font as! CGFloat) } else if font is UIFont { self.font = font as? UIFont } if let color = textColor { self.textColor = color } self.text = text } /// 等宽字体 convenience init(MonospacedFontSize size: CGFloat) { self.init() font = UIFont(name: "Helvetica Neue", size: size) } } <file_sep>/HungryTools/Classes/Category/UILabel+Size.swift // // UILabel+Size.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UILabel { /// 单行文本宽度 func textWidth() -> CGFloat { if numberOfLines == 0 { return bounds.size.width } return text?.size(withAttributes: [.font: font ?? UIFont.systemFont(ofSize: 17)]).width ?? 0 } /// 多行普通文本高度 func textHeightWithWidth(width: CGFloat) -> CGFloat { guard let textString = text as NSString? else { return 0 } return textString.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: font ?? 17], context: nil).size.height } /// 多行富文本高度(需先赋值 attributedText 属性) func attributedTextHeightWithWidth(width: CGFloat) -> CGFloat { guard let attri = attributedText else { return 0 } return attri.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).size.height } } <file_sep>/HungryTools/Classes/Category/UIView+Init.swift // // UIView+Init.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UIView { convenience init(backgroundColor: UIColor, radius: CGFloat = 0, frame: CGRect = .zero) { self.init() self.frame = frame self.backgroundColor = backgroundColor if radius > 0 { layer.cornerRadius = radius } } } <file_sep>/HungryTools/Classes/UITool/ZHCWeakProxy.swift // // ZHCWeakProxy.swift // HungryTools // // Created by 张海川 on 2021/3/5. // class ZHCWeakProxy: NSObject { weak var target: AnyObject? init(target: Any?) { self.target = target as AnyObject? super.init() } /// Fast forwarding 快速转发阶段(消息转发机制) override func forwardingTarget(for aSelector: Selector!) -> Any? { target } } <file_sep>/HungryTools/Classes/UITool/ZHCCountingButton.swift // // ZHCCountingButton.swift // HungryTools // // Created by 张海川 on 2019/12/21. // import UIKit public class ZHCCountingButton: UIButton { public enum CountingStatus { /// 未触发倒计时状态 case normal /// 正在倒计时 case counting /// 倒计时结束 case recovered } /// 用于防重置处理 static var allStamps: [String : TimeInterval]? public var countingStatus: CountingStatus = .normal public let recoveredTitle: String public let countingTitle: String /// 用于防重置标记,每个按钮不同 public var stamp: String? private let countingSeconds: Int private var nowSeconds: Int private var timer: Timer? deinit { timer?.invalidate() } public init(normalTitle: String, countingTitle: String, recoveredTitle: String, normalTitleColor: UIColor, countingTitleColor: UIColor, normalBackgroundColor: UIColor? = nil, countingBackgroundColor: UIColor? = nil, fontSize: CGFloat, countingSeconds: Int, stamp: String? = nil) { self.countingTitle = countingTitle self.recoveredTitle = recoveredTitle self.nowSeconds = countingSeconds self.countingSeconds = countingSeconds self.stamp = stamp super.init(frame: .zero) titleLabel?.font = UIFont(name: "Helvetica Neue", size: fontSize) // 等宽字体 setTitleColor(normalTitleColor, for: .normal) setTitleColor(countingTitleColor, for: .disabled) if let norBGColor = normalBackgroundColor { setBackgroundImage(UIImage.image(color: norBGColor), for: .normal) } if let disBGColor = countingBackgroundColor { setBackgroundImage(UIImage.image(color: disBGColor), for: .disabled) } setTitle(normalTitle, for: .normal) // 防重置 if let stamp = stamp, let interval = ZHCCountingButton.allStamps?[stamp] { let speedSeconds = Int(Date().timeIntervalSince1970 - interval) let leftSeconds = countingSeconds - speedSeconds if leftSeconds > 0 { nowSeconds = leftSeconds startCounting() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func startCounting () { countingStatus = .counting isEnabled = false if let stamp = stamp, nowSeconds == countingSeconds { if ZHCCountingButton.allStamps == nil { ZHCCountingButton.allStamps = [String : TimeInterval]() } ZHCCountingButton.allStamps![stamp] = Date().timeIntervalSince1970 } let weakProxy = ZHCWeakProxy(target: self) timer = Timer.scheduledTimer(timeInterval: 1, target: weakProxy, selector: #selector(countingEvent), userInfo: nil, repeats: true) timer!.fireDate = Date() } @objc func countingEvent() { nowSeconds -= 1 if nowSeconds == 0 { // 计时结束,重置时间 nowSeconds = countingSeconds timer?.invalidate() timer = nil isEnabled = true setTitle(recoveredTitle, for: .normal) if let stamp = stamp { ZHCCountingButton.allStamps?.removeValue(forKey: stamp) if ZHCCountingButton.allStamps?.isEmpty ?? false { ZHCCountingButton.allStamps = nil } } return } setTitle(String(format: countingTitle, nowSeconds), for: .disabled) } } <file_sep>/HungryTools/Classes/Category/UITableViewCell+Separator.swift // // UITableViewCell+Separator.swift // HungryTools // // Created by 张海川 on 2019/11/15. // import ObjectiveC.runtime var Key_isShowTopSeparatorLine = 0 public extension UITableViewCell { // var isShowTopSeparatorLine: Bool { // get { // objc_getAssociatedObject(self, &Key_isShowTopSeparatorLine) as! Bool // } // set { // objc_setAssociatedObject(self, &Key_isShowTopSeparatorLine, newValue, .OBJC_ASSOCIATION_ASSIGN) // // if newValue { // if viewWithTag(10086) == nil { // let separatorLine = UIView() // separatorLine.backgroundColor = .lightGray // separatorLine.tag = 10086 // addSubview(separatorLine) // separatorLine.snp.makeConstraints { (make) in // make.top.left.right.equalTo(self) // make.height.equalTo(0.5) // } // } // } else { // if let separatorLine = viewWithTag(10086) { // separatorLine.removeFromSuperview() // } // } // } // } } <file_sep>/HungryTools/Classes/Category/UIImageView+Init.swift // // UIImageView+Init.swift // HungryTools // // Created by 张海川 on 2019/11/19. // public extension UIImageView { convenience init(imageName: String) { self.init(image: UIImage(named: imageName)) } convenience init(cornerRadius: CGFloat, clips: Bool = true, contentMode: UIView.ContentMode = .scaleAspectFill) { self.init() layer.cornerRadius = cornerRadius clipsToBounds = clips self.contentMode = contentMode } } <file_sep>/HungryTools/Classes/Category/UIButton+Init.swift // // UIButton+Init.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UIButton { convenience init(title: String? = nil, titleColor: UIColor? = nil, font: Any? = nil, cornerRadius: CGFloat? = nil, backgroundColor: UIColor? = nil, target: Any? = nil, action: Selector? = nil) { self.init(type: .custom) setTitle(title, for: .normal) setTitleColor(titleColor, for: .normal) if font is Int { titleLabel?.font = .systemFont(ofSize: CGFloat(font as! Int)) } else if font is Double { titleLabel?.font = .systemFont(ofSize: CGFloat(font as! Double)) } else if font is CGFloat { titleLabel?.font = .systemFont(ofSize: font as! CGFloat) } else if font is UIFont { titleLabel?.font = font as? UIFont } if let radius = cornerRadius, radius > 0 { layer.cornerRadius = radius } self.backgroundColor = backgroundColor if target != nil && action != nil { addTarget(target, action: action!, for: .touchUpInside) } } convenience init(imageName: String, target: Any?, action: Selector) { self.init(type: .custom) setImage(UIImage(named: imageName), for: .normal) addTarget(target, action: action, for: .touchUpInside) } } <file_sep>/HungryTools/Classes/Category/String+Check.swift // // String+Check.swift // HungryTools // // Created by 张海川 on 2019/10/30. // import CommonCrypto public extension String { func checkWithRegexString(regex: String) -> Bool { NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self) } func MD5() -> String { let str = (self as NSString).cString(using: String.Encoding.utf8.rawValue) let strLen = CUnsignedInt((self as NSString).lengthOfBytes(using: String.Encoding.utf8.rawValue)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<UInt8>.allocate(capacity: 16) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0 ..< digestLen { hash.appendFormat("%02x", result[i]) } result.deinitialize(count: 16) return hash as String } func isPhoneNumber() -> Bool { checkWithRegexString(regex: "^1[3-9]\\d{9}$") } func isPassword() -> Bool { checkWithRegexString(regex: "^(?=.*\\d)(?=.*[A-Za-z]).{6,18}$") } func phoneFormat() -> String { if !self.isPhoneNumber() { return "" } let index2 = self.index(self.startIndex, offsetBy: 3) let index6 = self.index(self.startIndex, offsetBy: 7) let str1 = String(self.prefix(upTo: index2)) let str2 = String(self[index2 ..< index6]) let str3 = String(self.suffix(from: index6)) return str1 + " " + str2 + " " + str3 } /// 获取字符串字符数字 func charactersCount() -> UInt { let enc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue)) let da = self.data(using: String.Encoding.init(rawValue: enc)) return UInt(da?.count ?? 0) } } <file_sep>/HungryTools/Classes/Category/UIImage+Chameleon.swift // // UIImage+Chameleon.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension UIImage { enum DirectionType { /// 从上到下 case topToBottom /// 从左到右 case leftToRight /// 左上到右下 case upleftToLowright /// 右上到左下 case uprightToLowleft case custom(startPoint: CGPoint, endPoint: CGPoint) } /// 生成渐变色图片,默认方向从左到右 static func image(colors: [UIColor], direction: DirectionType? = .leftToRight, size: CGSize? = CGSize(width: 1, height: 1)) -> UIImage { let startPoint, endPoint: CGPoint switch direction! { case .topToBottom: startPoint = CGPoint(x: 0.5, y: 0) endPoint = CGPoint(x: 0.5, y: 1) case .leftToRight: startPoint = CGPoint(x: 0, y: 0.5) endPoint = CGPoint(x: 1, y: 0.5) case .upleftToLowright: startPoint = CGPoint(x: 0, y: 0) endPoint = CGPoint(x: 1, y: 1) case .uprightToLowleft: startPoint = CGPoint(x: 1, y: 0) endPoint = CGPoint(x: 0, y: 1) case let .custom(sPoint, ePoint): startPoint = sPoint endPoint = ePoint } let layer = CAGradientLayer() layer.startPoint = startPoint layer.endPoint = endPoint layer.colors = [colors[0].cgColor, colors[1].cgColor] layer.frame = CGRect(x: 0, y: 0, width: size!.width, height: size!.height) layer.locations = [0, 1] UIGraphicsBeginImageContextWithOptions(layer.frame.size, layer.isOpaque, 0.0) layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } <file_sep>/HungryTools/Classes/UITool/ZHCTextField.swift // // ZHCTextField.swift // HungryTools // // Created by 张海川 on 2019/12/25. // import UIKit public class ZHCTextField: UITextField { public enum TextFieldType { case normal case number case phoneNumber case phoneNumberWithoutSpacing /// 半角字符 包括字母,数字,标点符号 case password case money case idCardNumber /// 人名 可以输入汉字、英文字母和数字 case chinese case bankCardNumber } public var fieldType = TextFieldType.normal { didSet { switch fieldType { case .normal: break case .number: keyboardType = .numberPad case .phoneNumber: keyboardType = .phonePad maxLength = 13 case .phoneNumberWithoutSpacing: keyboardType = .phonePad maxLength = 11 case .password: isSecureTextEntry = true rightView = secureView rightViewMode = .always keyboardType = .alphabet maxLength = 18 case .money: keyboardType = .decimalPad maxLength = 8 case .idCardNumber: maxLength = 18 case .chinese: break case .bankCardNumber: keyboardType = .numberPad maxLength = 19 } } } /// 文本长度限制 public var maxLength = 0 /// 删除空格后的手机号码,在 ANFieldType 为 ANFieldTypePhoneNumber 时有效。 public var phoneNumberString: String? { get { if fieldType == .phoneNumber { return text?.replacingOccurrences(of: " ", with: "") } else { return nil } } } // MARK: - 左视图 /// 左视图文字颜色,需在leftText之前赋值 public var leftTextColor: UIColor? /// 左视图文字字体,需在leftText之前赋值 public var leftTextFontSize: CGFloat = 14 /// 左视图文字宽度,需在leftText之前赋值 public var leftTextWidth: CGFloat? /// 左视图文字对齐方式,需在leftText之前赋值 public var leftTextLabelAlignment: NSTextAlignment = .left public var leftText: String? { didSet { let label = UILabel() label.font = UIFont.systemFont(ofSize: leftTextFontSize) if let _ = leftTextColor { label.textColor = leftTextColor! } label.textAlignment = leftTextLabelAlignment // let leftView = UIView(frame: CGRect(x: 0, y: 0, width: label.textWidth() + 21, height: bounds.size.height)) let leftView = UIView() leftView.addSubview(label) addLeftViewConstraints(with: leftView, subView: label) if let _ = leftTextWidth { leftView.addConstraint(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: leftTextWidth!)) } self.leftView = leftView leftViewMode = .always } } public var leftImageName: String? { didSet { guard leftImageName != nil else { return } guard let image = UIImage(named: leftImageName!) else { return } let subView = UIImageView(image: image) let leftView = UIView(frame: CGRect(x: 0, y: 0, width: image.size.width + 20, height: bounds.size.height)) leftView.addSubview(subView) addLeftViewConstraints(with: leftView, subView: subView) self.leftView = leftView leftViewMode = .always } } public override var leftView: UIView? { didSet { updateBottomLineConstraints() } } // MARK: - 右视图 public override var rightView: UIView? { didSet { updateBottomLineConstraints() } } // MARK: - 占位符 public var placeholderColor: UIColor? { didSet { setPlaceHolderAttribute(value: placeholderColor!) } } public var placeholderFont: UIFont? { didSet { setPlaceHolderAttribute(value: placeholderFont!) } } public override var placeholder: String? { didSet { if placeholderColor != nil { setPlaceHolderAttribute(value: placeholderColor!) } if placeholderFont != nil { setPlaceHolderAttribute(value: placeholderFont!) } } } // MARK: - /// 密码明暗文切换图片数组,需包含两个UIImage,第一个代表明文,第二个代表暗文。 public var secureButtonImages: [UIImage]? { didSet { guard secureButtonImages?.count == 2 else { return } secureButton.setImage(secureButtonImages![0], for: .selected) secureButton.setImage(secureButtonImages![1], for: .normal) } } /// clearButton 按钮图片 public var clearButtonImage: UIImage? { didSet { let button = value(forKey: "_clearButton") as! UIButton button.setImage(clearButtonImage, for: .normal) } } public var showBottomLine = true { didSet { bottomLineView.isHidden = !showBottomLine } } /// 正在输入时下划线颜色 public var bottomLineActiveColor = UIColor.purple /// 失去焦点时下划线颜色 public var bottomLinePassiveColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1) { didSet { bottomLineView.backgroundColor = bottomLinePassiveColor } } /// 下划线高度,默认0.5 public var bottomLineHeight: CGFloat = 0.5 { didSet { removeConstraints(bottomLineView.constraints) let margin: CGFloat = isContainLeftOrRightView ? 10 : 0 addConstraints([ NSLayoutConstraint(item: bottomLineView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: margin), NSLayoutConstraint(item: bottomLineView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: bottomLineView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: margin), NSLayoutConstraint(item: bottomLineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bottomLineHeight), ]) } } private lazy var bottomLineView: UIView = { let view = UIView() view.backgroundColor = bottomLinePassiveColor return view }() private lazy var secureView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 64, height: 30)) secureButton.frame = CGRect(x: 10, y: 0, width: 44, height: 30) view.addSubview(secureButton) return view }() private lazy var secureButton: UIButton = { let button = UIButton(imageName: "icon_mmbkj_24", target: self, action: #selector(secureBtnClicked)) button.setImage(UIImage(named: "icon_mmkj_24"), for: .selected) return button }() private var isContainLeftOrRightView = false override init(frame: CGRect) { super.init(frame: frame) initConfig() } required init?(coder: NSCoder) { super.init(coder: coder) initConfig() } fileprivate func initConfig() { clearButtonMode = .whileEditing delegate = self font = .systemFont(ofSize: 14) addBottomLine() } // MARK: - Click Event @objc private func secureBtnClicked() { isSecureTextEntry = !isSecureTextEntry secureButton.isSelected = !isSecureTextEntry } } extension ZHCTextField: UITextFieldDelegate { public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // 删除 if string == "" { return true } let comingTextLength = (textField.text?.count ?? 0) + string.count - range.length if maxLength > 0 && comingTextLength > maxLength { return false } switch fieldType { case .normal: return true case .number: return string.checkWithRegexString(regex: "[0-9]+") case .phoneNumber: if textField.text?.count == 3 || textField.text?.count == 8 { textField.text?.insert(" ", at: textField.text!.endIndex) } return string.checkWithRegexString(regex: "[0-9]+") case .phoneNumberWithoutSpacing: return string.checkWithRegexString(regex: "[0-9]+") case .password: return string.checkWithRegexString(regex: "[\\x00-\\xff]+") // 半角字符 包括字母,数字,标点符号 case .money: return string.checkWithRegexString(regex: "[0-9.]+") case .idCardNumber: return string.checkWithRegexString(regex: "[0-9Xx]+") case .chinese: return string.checkWithRegexString(regex: "[a-z\\u4e00-\\u9fa5]+") case .bankCardNumber: return string.checkWithRegexString(regex: "[0-9]+") } } public func textFieldDidBeginEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.25) { self.bottomLineView.backgroundColor = self.bottomLineActiveColor } } public func textFieldDidEndEditing(_ textField: UITextField) { UIView.animate(withDuration: 0.25) { self.bottomLineView.backgroundColor = self.bottomLinePassiveColor } } } // MARK: - tools private extension ZHCTextField { func addLeftViewConstraints(with leftView: UIView, subView: UIView) { subView.translatesAutoresizingMaskIntoConstraints = false leftView.addConstraints([ NSLayoutConstraint(item: subView, attribute: .centerY, relatedBy: .equal, toItem: leftView, attribute: .centerY, multiplier: 1, constant: 0), NSLayoutConstraint(item: subView, attribute: .left, relatedBy: .equal, toItem: leftView, attribute: .left, multiplier: 1, constant: 10), NSLayoutConstraint(item: subView, attribute: .right, relatedBy: .equal, toItem: leftView, attribute: .right, multiplier: 1, constant: -10), ]) } func addBottomLine() { addSubview(bottomLineView) bottomLineView.translatesAutoresizingMaskIntoConstraints = false addConstraints([ NSLayoutConstraint(item: bottomLineView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0), NSLayoutConstraint(item: bottomLineView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: bottomLineView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0), NSLayoutConstraint(item: bottomLineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bottomLineHeight) ]) } func updateBottomLineConstraints() { isContainLeftOrRightView = true removeConstraints(bottomLineView.constraints) addConstraints([ NSLayoutConstraint(item: bottomLineView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 10), NSLayoutConstraint(item: bottomLineView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0), NSLayoutConstraint(item: bottomLineView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: -10), NSLayoutConstraint(item: bottomLineView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: bottomLineHeight) ]) } func setPlaceHolderAttribute(value: Any) { guard attributedPlaceholder != nil else { return } let attriString = NSMutableAttributedString(attributedString: attributedPlaceholder!) var name = NSAttributedString.Key.font if value is UIFont { name = .font } else if value is UIColor { name = .foregroundColor } attriString.addAttribute(name, value: value, range: NSRange(location: 0, length: attributedPlaceholder!.length)) attributedPlaceholder = attriString } } //private extension String { // // func checkWithRegexString(regex: String) -> Bool { // NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: self) // } //} <file_sep>/Example/HungryTools/CountingButtonController.swift // // CountingButtonController.swift // HungryTools_Example // // Created by 张海川 on 2021/3/5. // Copyright © 2021 CocoaPods. All rights reserved. // import UIKit import HungryTools class CountingButtonController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationItem.title = "CountingButton" view.backgroundColor = .white let countingButton = ZHCCountingButton(normalTitle: "获取验证码", countingTitle: "(%d)", recoveredTitle: "重新获取", normalTitleColor: .black, countingTitleColor: .lightGray, fontSize: 14, countingSeconds: 60) countingButton.frame = CGRect(x: 50, y: 200, width: 100, height: 32) countingButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside) view.addSubview(countingButton) } @objc func buttonClicked(sender: ZHCCountingButton) { sender.startCounting() } } <file_sep>/Example/HungryTools/ViewController.swift // // ViewController.swift // HungryTools // // Created by zhanghaichuan on 03/05/2021. // Copyright (c) 2021 zhanghaichuan. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { let dataArray = ["CountingButton"] lazy var mainTableView: UITableView = { let tableView = UITableView(frame: .zero, style: .plain) tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") return tableView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.title = "HungryTools" view.backgroundColor = .white view.addSubview(mainTableView) mainTableView.snp.makeConstraints { (make) in make.edges.equalTo(view) } } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { dataArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath) cell.textLabel?.text = dataArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let nextVC: UIViewController? switch dataArray[indexPath.row] { case "CountingButton": nextVC = CountingButtonController() default: nextVC = nil } if let vc = nextVC { navigationController?.pushViewController(vc, animated: true) } } } <file_sep>/HungryTools/Classes/Category/UIImage+Compress.swift // // UIImage+Compress.swift // HungryTools // // Created by 张海川 on 2019/12/5. // public extension UIImage { /// 压缩图片质量,如果图片太大压缩不到目标大小,则减小尺寸重绘再压缩 func compressImage(aimMB: CGFloat) -> Data { let aimBytes = Int(aimMB * 1024 * 1024) var max: CGFloat = 1 var min: CGFloat = 0 var data = UIImageJPEGRepresentation(self, 1)! // print("原始图片大小:\(CGFloat(data.count) / 1024 / 1024)MB") if data.count < aimBytes { return data } for _ in 0..<6 { let quality = (min + max) / 2 data = UIImageJPEGRepresentation(self, quality)! // print("第\(i + 1)次压缩,比例:\(quality),图片大小:\(CGFloat(data.count) / 1024 / 1024)MB") if data.count > aimBytes { max = quality } else if data.count < Int(CGFloat(aimBytes) * 0.9) { min = quality } else { break } } if data.count <= aimBytes { return data } var newImage = self print("宽:\(newImage.size.width)高:\(newImage.size.height)") while data.count > aimBytes { let ratio = CGFloat(aimBytes) / CGFloat(data.count) let rect = CGRect(x: 0, y: 0, width: Int(newImage.size.width * sqrt(ratio)), height: Int(newImage.size.height * sqrt(ratio))) UIGraphicsBeginImageContext(rect.size) newImage.draw(in: rect) newImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() data = UIImageJPEGRepresentation(self, (min + max) / 2)! // print("缩小尺寸,比例:\(ratio),图片大小:\(CGFloat(data.count) / 1024 / 1024)MB,宽:\(rect.size.width)高:\(rect.size.height)") } return data } } <file_sep>/HungryTools/Classes/Category/String+Attributed.swift // // String+Attributed.swift // HungryTools // // Created by 张海川 on 2019/11/15. // public extension String { func setLineSpacing(_ lineSpacing: CGFloat) -> NSMutableAttributedString { addAttributes(dictionary: ["lineSpacing": lineSpacing]) } func addAttributeColor(color: UIColor, range: NSRange) -> NSMutableAttributedString { addAttributes(dictionary: ["color": color, "colorRange": range]) } func addAttributeFontSize(fontSize: CGFloat, range: NSRange) -> NSMutableAttributedString { addAttributes(dictionary: ["fontSize": fontSize, "fontSizeRange": range]) } /// 传入数字时需要用 CGFloat(x) 明确类型 func addAttributes(dictionary: [String : Any]) -> NSMutableAttributedString { let attri = NSMutableAttributedString(string: self) if let color = dictionary["color"], let colorRange = dictionary["colorRange"] as? NSRange { attri.addAttribute(.foregroundColor, value: color, range: colorRange) } if let fontSize = dictionary["fontSize"] as? CGFloat, let fontRange = dictionary["fontSizeRange"] as? NSRange { let font = UIFont.systemFont(ofSize: fontSize) attri.addAttribute(.font, value: font, range: fontRange) } if let spacing = dictionary["lineSpacing"] as? CGFloat { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = spacing attri.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: self.count)) } return attri } func width(withFont font: UIFont) -> CGFloat { self.size(withAttributes: [.font: font]).width } enum Pai_CalculatesSizeType { case width case height } func calculates(type: Pai_CalculatesSizeType, maxValue: CGFloat, font: UIFont) -> CGFloat { let nStr = self as NSString var size: CGSize switch type { case .width: size = CGSize(width: CGFloat(MAXFLOAT), height: maxValue) return nStr.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).width case .height: size = CGSize(width: maxValue, height: CGFloat(MAXFLOAT)) return nStr.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).height } } func attributedString(withLineHeight height: CGFloat, font: UIFont) -> NSAttributedString { let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle paragraphStyle.minimumLineHeight = height paragraphStyle.maximumLineHeight = height let baselineOffset = (height - font.lineHeight) / 4 let contentAttr = NSAttributedString(string: self, attributes: [NSAttributedString.Key.paragraphStyle:paragraphStyle, NSAttributedString.Key.baselineOffset:baselineOffset, NSAttributedString.Key.font:font]) return contentAttr } }
9aaa6b44fb00c5cafd524e81c3f75097032b6726
[ "Swift" ]
16
Swift
HungryZ/HungryTools
bfd19fc257f18f2e5a263e7874d753d6225c8f03
27cee67a2f275d5687b73505eaa305f31b3b90b2
refs/heads/master
<file_sep><div class="heading_bg"> <h2>Live Auction</h2> </div> <p><strong>Open Bid</strong><br> <ul class="ca-menu" style="margin: 40px 0"> <?php $id = 0; foreach ($auction as $key ) { if ($id % 4 == 0) { ?> </ul> <ul class="ca-menu" style="margin: 40px 0; padding"> <?php } ?> <li style="margin-top:15px"> <a href="#"> <span class="ca-icon"><img src="<?php echo base_url()."uploads/".$key->image_name?>" width="230px" height="200px"></span> <div class="ca-content"> <input type="hidden" name="auction_id" value="<?php echo $key->auction_id?>"> <h2 class="ca-main" style="margin:0"><button class="button-bid" type="button" onclick="bidNow(this);">Bid Now</button></h2> <h3 class="ca-sub">Rp <?php echo $key->amount; ?></h3> </div> </a> </li> <?php $id++; } ?> </ul> <div style="clear:both; height: 40px"></div> <script> function bidNow(val) { var base_url = '<?php echo base_url(); ?>'; var login = <?php echo $login ?>; if (login != 1) { alert('Please Log In to Your Account'); } else{ window.location.href = base_url + 'index.php/auction/detail/' + $(val).parent().prev().val(); } } </script><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Landing extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library("Ion_auth"); $this->id = $this->ion_auth->get_user_id(); $this->isAdmin = $this->ion_auth->is_admin($this->id); $this->login = false; if ($this->ion_auth->logged_in()){ $this->login = true; } $this->load->model('auction_model'); } public function index() { $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $data['login'] = $this->login ? 1 : 0; $data['auction'] = $this->auction_model->get_closed_auction(); $data['auctiontopfour'] = $this->auction_model->get_auction_top_four(); $view = array( 'content' => $this->load->view('landing/index', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function contact_us() { $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('landing/contact_us', '', TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function live_auction() { $data['auction'] = $this->auction_model->get_open_auction(); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $data['login'] = $this->login ? 1 : 0; $view = array( 'content' => $this->load->view('landing/live_auction', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function tracking() { if ($this->input->post()) { if ($this->input->post('awb_numbers') != '') { $data['search'] = $this->auction_model->tracking_search($this->input->post('awb_numbers')); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('landing/tracking_search', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('landing/tracking', '', TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } <file_sep><table border="0"> <th>AWB No.</th> <th>Origin</th> <th>Destination</th> <th>Date of Shipment</th> <th>Status</th> <tr> <td><?php echo $search->awb_number; ?></td> <td><?php echo $search->origin; ?></td> <td><?php echo $search->destination; ?></td> <td><?php echo date('Y M d',strtotime($search->date_of_shipment)); ?></td> <td><?php echo $search->status; ?></td> </tr> </table><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('auction_model'); $this->load->library("Ion_auth"); $this->id = $this->ion_auth->get_user_id(); $this->isAdmin = $this->ion_auth->is_admin($this->id); $this->load->library('pagination'); $this->login = false; if(!$this->ion_auth->logged_in()) { redirect("auth/login"); } else{ $this->login = true; if (!$this->isAdmin) { redirect("error/not_authorized"); } } } public function index() { $limit = 10; $auction = $this->auction_model->get_all_auction(); //pagination configuration $config = array(); $config["base_url"] = base_url() . "index.php/admin/index"; $total_row = count($auction); $config["total_rows"] = $total_row; $config["per_page"] = $limit; $config['use_page_numbers'] = TRUE; $config['num_links'] = $total_row; $config['cur_tag_open'] = '&nbsp;<a class="current">'; $config['cur_tag_close'] = '</a>'; $config['next_link'] = 'Next'; $config['prev_link'] = 'Previous'; $this->pagination->initialize($config); if($this->uri->segment(3)){ $page = ($this->uri->segment(3)) ; } else{ $page = 1; } $page = ($page-1) * $limit; $data["auctions"] = $this->auction_model->get_auction_page($config["per_page"], $page); $str_links = $this->pagination->create_links(); $data["links"] = explode('&nbsp;',$str_links ); //get the posts data $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/index',$data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function post_auction() { $this->form_validation->set_rules('fish_name', 'Fish Name', 'required'); $this->form_validation->set_rules('qty', 'Qty', 'required|decimal'); $this->form_validation->set_rules('amount', 'Price', 'required|decimal'); $this->form_validation->set_rules('open_bid', 'Open Bid Date', 'required'); $this->form_validation->set_rules('close_bid', 'Closed Bid Date', 'required'); $this->form_validation->set_rules('descriptions', 'Description', 'required'); $this->form_validation->set_rules('file_name', 'Image File', 'required'); $data['error_upload'] = ''; if ($this->input->post()) { if ($this->form_validation->run() == TRUE) { $insert = $this->auction_model->insert_auction(); if ($insert != 'success') { $data['error_upload'] = $insert; } else { redirect('admin/index'); return false; } } } $data['viewmodel'] = $this->auction_model->create_auction_model(); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/post_auction', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function edit_auction($id) { $this->form_validation->set_rules('fish_name', 'Fish Name', 'required'); $this->form_validation->set_rules('qty', 'Qty', 'required|decimal'); $this->form_validation->set_rules('amount', 'Price', 'required|decimal'); $this->form_validation->set_rules('open_bid', 'Open Bid Date', 'required'); $this->form_validation->set_rules('close_bid', 'Closed Bid Date', 'required'); $this->form_validation->set_rules('descriptions', 'Description', 'required'); $this->form_validation->set_rules('file_name', 'Image File', 'required'); $data['error_upload'] = ''; if ($this->input->post()) { if ($this->form_validation->run() == TRUE) { $insert = $this->auction_model->save_auction($id); if ($insert != 'success') { $data['error_upload'] = $insert; } else { redirect('admin/index'); return false; } } } $data['auction_id'] = $id; $data['viewmodel'] = $this->auction_model->edit_auction_model($id); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/edit_auction', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function delete_auction($id) { $filename = $this->auction_model->get_filename($id); if (!empty($filename)) { unlink('./uploads/'.$filename); $this->auction_model->delete_auction($id); } redirect('admin/index'); } public function payment() { $limit = 10; $auction = $this->auction_model->get_for_check_payment(); //pagination configuration $config = array(); $config["base_url"] = base_url() . "index.php/admin/payment"; $total_row = count($auction); $config["total_rows"] = $total_row; $config["per_page"] = $limit; $config['use_page_numbers'] = TRUE; $config['num_links'] = $total_row; $config['cur_tag_open'] = '&nbsp;<a class="current">'; $config['cur_tag_close'] = '</a>'; $config['next_link'] = 'Next'; $config['prev_link'] = 'Previous'; $this->pagination->initialize($config); if($this->uri->segment(3)){ $page = ($this->uri->segment(3)) ; } else{ $page = 1; } $page = ($page-1) * $limit; $data["auctions"] = $this->auction_model->get_for_check_payment_page($config["per_page"], $page); $str_links = $this->pagination->create_links(); $data["links"] = explode('&nbsp;',$str_links ); //get the posts data $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/payment',$data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function confirm_payment($id) { if ($this->auction_model->checktrackingdb($id) == 0) { $this->auction_model->update_payment($id); $resi = $this->auction_model->gettrackingnumber($id); $this->load->library('email'); $config['protocol'] = "smtp"; $config['smtp_host'] = "ssl://smtp.gmail.com"; $config['smtp_port'] = "465"; $config['smtp_user'] = ""; $config['smtp_pass'] = ""; $config['charset'] = "utf-8"; $config['mailtype'] = "html"; $config['newline'] = "\r\n"; $this->email->initialize($config); $emailwinner = $this->auction_model->get_winner_email($id); $this->email->from('<EMAIL>', 'Blabla'); $this->email->to($emailwinner); $this->email->subject('E-Fishauction Confirmation Payment'); $this->email->message('Congratulation you have done the transaction!! Check your tracking status on Tracking Page, your AWB Number is '.$resi); $this->email->send(); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $data['status'] = 'Email have been sent to '.$emailwinner. ' update tracking with AWB.No '.$resi; $view = array( 'content' => $this->load->view('auction/auction_notif', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } public function tracking() { $limit = 10; $auction = $this->auction_model->get_for_check_tracking(); //pagination configuration $config = array(); $config["base_url"] = base_url() . "index.php/admin/tracking"; $total_row = count($auction); $config["total_rows"] = $total_row; $config["per_page"] = $limit; $config['use_page_numbers'] = TRUE; $config['num_links'] = $total_row; $config['cur_tag_open'] = '&nbsp;<a class="current">'; $config['cur_tag_close'] = '</a>'; $config['next_link'] = 'Next'; $config['prev_link'] = 'Previous'; $this->pagination->initialize($config); if($this->uri->segment(3)){ $page = ($this->uri->segment(3)) ; } else{ $page = 1; } $page = ($page-1) * $limit; $data["auctions"] = $this->auction_model->get_for_check_tracking_page($config["per_page"], $page); $str_links = $this->pagination->create_links(); $data["links"] = explode('&nbsp;',$str_links ); //get the posts data $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/tracking',$data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } public function tracking_update($id) { if ($this->input->post()) { $insert = $this->auction_model->tracking_update($this->input->post('tracking_id')); redirect('admin/tracking'); } $data['auction_id'] = $id; $data['viewmodel'] = $this->auction_model->tracking_model($id); $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('admin/tracking_update', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } <file_sep><style> ul.tsc_pagination li a { border:solid 1px; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; padding:6px 9px 6px 9px; } ul.tsc_pagination li { padding-bottom:1px; } ul.tsc_pagination li a:hover, ul.tsc_pagination li a.current { color:#FFFFFF; box-shadow:0px 1px #EDEDED; -moz-box-shadow:0px 1px #EDEDED; -webkit-box-shadow:0px 1px #EDEDED; } ul.tsc_pagination { margin:4px 0; padding:0px; height:100%; overflow:hidden; font:12px 'Tahoma'; list-style-type:none; } ul.tsc_pagination li { float:left; margin:0px; padding:0px; margin-left:5px; margin-top: 10px; } ul.tsc_pagination li a { color:black; display:block; text-decoration:none; padding:7px 10px 7px 10px; } ul.tsc_pagination li a img { border:none; } ul.tsc_pagination li a { color:#0A7EC5; border-color:#8DC5E6; background:#F8FCFF; display:inline; } ul.tsc_pagination li a:hover, ul.tsc_pagination li a.current { text-shadow:0px 1px #388DBE; border-color:#3390CA; background:#58B0E7; background:-moz-linear-gradient(top, #B4F6FF 1px, #63D0FE 1px, #58B0E7); background:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0.02, #B4F6FF), color-stop(0.02, #63D0FE), color-stop(1, #58B0E7)); } </style> <h2>Tracking</h2> <table border="0"> <th>Fish Name</th> <th>Qty</th> <th>Price</th> <th>Winner</th> <th>Deal</th> <th>Open Bid</th> <th>Close Bid</th> <th>Payment</th> <?php foreach ($auctions as $key) { ?> <tr> <td><?php echo $key->fish_name; ?></td> <td><?php echo $key->qty; ?></td> <td><?php echo $key->amount; ?></td> <td><?php echo $key->username; ?></td> <td><?php echo $key->deal_amount; ?></td> <td><?php echo $key->open_bid; ?></td> <td><?php echo $key->close_bid; ?></td> <td> <a href="<?php echo base_url().'index.php/admin/tracking_update/'.$key->auction_id;?>" class="button">Update Tracking</a> </td> </tr> <?php } ?> </table> <div id="pagination"> <ul class="tsc_pagination"> <!-- Show pagination links --> <?php foreach ($links as $link) { echo "<li>". $link."</li>"; } ?> </div><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed'); class Auction extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library("Ion_auth"); $this->id = $this->ion_auth->get_user_id(); $this->isAdmin = $this->ion_auth->is_admin($this->id); $this->login = false; if($this->ion_auth->logged_in()) { $this->login = true; } $this->load->model('auction_model'); $this->load->helper('date'); } public function detail($id) { if($this->ion_auth->logged_in()) { $data['detail'] = $this->auction_model->get_auction_by_id($id); $data['viewmodel'] = $this->auction_model->bid_model($id, $this->id); $data['winnername'] = ''; $data['dealamount'] = ''; $winnerId = $this->auction_model->get_auction_by_id($id)->winner; if (strlen($winnerId) > 0) { $data['winnername'] = $this->auction_model->get_username($winnerId); $data['dealamount'] = $this->auction_model->get_auction_by_id($id)->deal_amount; } $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('auction/detail', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } else{ redirect('auth/login'); } } public function bid() { if($this->ion_auth->logged_in()) { if ($this->input->post('amount') == '' || $this->input->post('amount') == 'NaN') { redirect('auction/detail/'.$this->input->post('auction_id')); } else{ $currentprice = $this->auction_model->check_current_price($this->input->post('auction_id')); if ($currentprice > $this->input->post('amount')) { $data['status'] = 'Price must be higher.'; } else{ $bid = $this->auction_model->bid_now(); $data['status'] = 'Success.'; if ($bid == 'closed') { $data['status'] = 'Sorry, auction is closed.'; } else if($bid == 'next'){ $data['status'] = 'Sorry, auction unopened.'; } } $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('auction/auction_notif', $data, TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } else{ redirect('auth/login'); } } } <file_sep><h1>Tracking</h1> <?php echo form_open('landing/tracking');?> <div class="one-half"> <fieldset> <label>Your AWB.No</label> <?php echo form_input('awb_numbers'); ?> </fieldset> </div> <div class="one-half last"> </div> <div style="clear:both; height: 40px;"> <fieldset> <input name="Mysubmitted" id="Mysubmitted" value="Search" class="button white button-submit" type="submit"> </fieldset> </div> </form><file_sep> <!-- tab panes --> <div id="prod_wrapper"> <div id="panes"> <div style="display:block"> <img src="<?php echo base_url()."uploads/".$detail->image_name?>" alt="" width="379px" width="225px"> <h5>Close Bid : <?php echo date('Y-M-d H:i:s',strtotime($detail->close_bid)) ?></h5> <p style="color:#2997AB;"><?php echo $winnername.' - Rp '.$dealamount; ?></p> <p style="text-align:right; margin-right: 16px"> <?php echo form_open('auction/bid'); echo form_input($viewmodel['user_id']); echo form_input($viewmodel['close_bid']); echo form_input($viewmodel['open_bid']); echo form_input($viewmodel['auction_id']); echo form_input($viewmodel['amount']); ?> <button class="button" type="submit">Bid Now!</button></p> <?php echo form_close(); ?> <p> Fish Name : <?php echo $detail->fish_name; ?> <br/>Price : Rp <?php echo $detail->amount; ?><br/> Qty : <?php echo $detail->qty; ?> gr</p> <p><?php echo $detail->description; ?></p> </div> </div> <!-- END tab panes --> <br clear="all"> <!-- close navigator --> </div> <script type="text/javascript"> $('.numeric').blur(function(){ var input = parseFloat($(this).val()).toFixed(1); $(this).val(input); }); </script><file_sep><h1>Update Tracking</h1> <?php echo form_open('admin/tracking_update/0');?> <div class="one-half"> <fieldset> <label>AWB.No</label> <?php echo form_input($viewmodel['awb_number']); ?> <?php echo form_input($viewmodel['tracking_id']); ?> </fieldset> <fieldset> <label>Origin</label> <?php echo form_input($viewmodel['origin']); ?> </fieldset> <fieldset> <label>Destination</label> <?php echo form_input($viewmodel['destination']);?> </fieldset> <fieldset> <label>Date of Shipment</label> <?php echo form_input($viewmodel['date_of_shipment']); ?> </fieldset> <fieldset> <label>Status</label> <?php echo form_input($viewmodel['status']);?> </fieldset> </div> <div class="one-half last"> </div> <div style="clear:both; height: 40px;"> <fieldset> <input name="Mysubmitted" id="Mysubmitted" value="Update" class="button white button-submit" type="submit"> </fieldset> </div> </form><file_sep><h1><?php echo lang('login_heading');?></h1> <p><?php echo lang('login_subheading');?></p> <div id="infoMessage"><?php echo $message;?></div> <div class="one-half"> <?php echo form_open("auth/login");?> <fieldset> <?php echo lang('login_identity_label', 'identity');?> <?php echo form_input($identity);?> </fieldset> <fieldset> <?php echo lang('login_password_label', 'password');?> <?php echo form_input($password);?> </fieldset> <fieldset><input name="Mysubmitted" id="Mysubmitted" value="Login" class="button white button-submit" type="submit"></fieldset> <?php echo form_close();?> </div> <div class="one-half last"> </div> <div style="clear:both; height: 40px;"> <p><a href=<?php echo base_url().'index.php/auth/register'?>>Create New Account</a></p> </div><file_sep><?php class Error extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library("Ion_auth"); $this->id = $this->ion_auth->get_user_id(); $this->isAdmin = $this->ion_auth->is_admin($this->id); $this->login = false; if ($this->ion_auth->logged_in()){ $this->login = true; } } public function not_authorized() { $menu['isAdmin'] = $this->isAdmin; $menu['login'] = $this->login; $view = array( 'content' => $this->load->view('errors/html/error_not_authorized', '', TRUE), 'menu' => $this->load->view('menu', $menu, TRUE) ); $this->load->view('master',$view); } } ?><file_sep><!DOCTYPE HTML> <head> <title>E-Fishauction</title> <meta charset="utf-8"> <!-- CSS Files --> <link rel="stylesheet" type="text/css" media="screen" href="<?php echo base_url();?>template/css/style.css"> <link rel="stylesheet" type="text/css" media="screen" href="<?php echo base_url();?>template/menu/css/simple_menu.css"> <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/js/fancybox/jquery.fancybox.css" media="all"> <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>template/boxes/css/style5.css"> <!--JS FILES --> <script src="<?php echo base_url();?>template/js/jquery.min.js"></script> <script src="<?php echo base_url();?>template/js/jquery.tools.min.js"></script> <script src="<?php echo base_url();?>template/js/twitter/jquery.tweet.js"></script> <script src="<?php echo base_url();?>template/js/modernizr/modernizr-2.0.3.js"></script> <script src="<?php echo base_url();?>template/js/easing/jquery.easing.1.3.js"></script> <script src="<?php echo base_url();?>template/js/kwicks/jquery.kwicks-1.5.1.pack.js"></script> <script src="<?php echo base_url();?>template/js/swfobject/swfobject.js"></script> <!-- FancyBox --> <script src="<?php echo base_url();?>template/js/fancybox/jquery.fancybox-1.2.1.js"></script> <script> $(function () { $("#prod_nav ul").tabs("#panes > div", { effect: 'fade', fadeOutSpeed: 400 }); }); </script> <script> $(document).ready(function () { $(".pane-list li").click(function () { window.location = $(this).find("a").attr("href"); return false; }); }); function get_filename(val) { $("#file_name").val(val.value); }; </script> </head> <body> <div class="header"> <!-- Logo/Title --> <div id="site_title"> <a href="<?php echo base_url()?>"> <img src="<?php echo base_url();?>template/img/logo.png" alt="" width="250px"> </a> </div> <!-- Main Menu --> <?php print $menu; ?> </div> <!-- END header --> <div id="container"> <!-- tab panes --> <?php print $content; ?> </div> <!-- END container --> <div id="footer"> <!-- First Column --> <div class="one-fourth"> <h3>Useful Links</h3> <ul class="footer_links"> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Ellem Ciet</a></li> <li><a href="#">Currivitas</a></li> <li><a href="#">Salim Aritu</a></li> </ul> </div> <!-- Second Column --> <div class="one-fourth"> <h3>Terms</h3> <ul class="footer_links"> <li><a href="#">Lorem Ipsum</a></li> <li><a href="#">Ellem Ciet</a></li> <li><a href="#">Currivitas</a></li> <li><a href="#">Salim Aritu</a></li> </ul> </div> <!-- Third Column --> <div class="one-fourth"> <h3>Information</h3> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sit amet enim id dui tincidunt vestibulum rhoncus a felis. <div id="social_icons"> Theme by <a href="http://www.csstemplateheaven.com">CssTemplateHeaven</a><br> Photos © <a href="http://dieterschneider.net"><NAME></a> </div> </div> <!-- Fourth Column --> <div class="one-fourth last"> <h3>Socialize</h3> <img src="<?php echo base_url();?>template/img/icon_fb.png" alt=""> <img src="<?php echo base_url();?>template/img/icon_twitter.png" alt=""> <img src="<?php echo base_url();?>template/img/icon_in.png" alt=""> </div> <div style="clear:both"></div> </div> <!-- END footer --> </body> </html><file_sep><ol id="menu"> <li><a href="<?php echo base_url();?>index.php/landing/index">Home</a> </li> <!-- end sub menu --> <li><a href="#">Auction</a> <!-- sub menu --> <ol> <li><a href="<?php echo base_url();?>index.php/landing/live_auction">Live Auction</a></li> </ol> </li> <!-- end sub menu --> <li><a href="<?php echo base_url();?>index.php/landing/tracking">Tracking</a></li> <?php if ($login && $isAdmin) { ?> <li><a href="#">Admin</a> <!-- sub menu --> <ol> <li><a href="<?php echo base_url();?>index.php/admin/index">List Auction</a></li> <li><a href="<?php echo base_url();?>index.php/admin/post_auction">Post Auction</a></li> <li><a href="<?php echo base_url();?>index.php/admin/payment">Payment</a></li> <li><a href="<?php echo base_url();?>index.php/admin/tracking">Tracking</a></li> </ol> </li> <?php }?> <?php if (!$login) { ?> <li><a href="<?php echo base_url();?>index.php/auth/login">Login</a></li> <?php }else{ ?> <li><a href="<?php echo base_url();?>index.php/auth/logout">Logout</a></li> <?php } ?> </ol><file_sep><?php class Auction_model extends CI_Model { public function __construct() { $this->load->library('session'); $this->load->helper('date'); } function create_auction_model(){ $data['image_file'] = array( 'name'=>'image_file', 'id'=>'image_file', 'type' => 'file', 'accept' => 'image/*', 'class' => 'text', 'onchange' => 'get_filename(this);' ); $data['file_name'] = array( 'name'=>'file_name', 'id'=>'file_name', 'type' => 'hidden', ); $data['fish_name'] = array( 'name'=>'fish_name', 'id'=>'fish_name', 'type' => 'text', 'class' => 'text' ); $data['qty'] = array( 'name'=>'qty', 'id'=>'qty', 'type' => 'text', 'class' => 'text numeric', ); $data['amount'] = array( 'name'=>'amount', 'id'=>'amount', 'type' => 'text', 'class' => 'text numeric' ); $data['open_bid'] = array( 'name'=>'open_bid', 'id'=>'open_bid', 'type' => 'date', 'class' => 'text dp' ); $data['open_bid_time'] = array( 'name'=>'open_bid_time', 'id'=>'open_bid_time', 'type' => 'text', 'class' => 'text tp' ); $data['close_bid'] = array( 'name'=>'close_bid', 'id'=>'close_bid', 'type' => 'date', 'class' => 'text dp' ); $data['close_bid_time'] = array( 'name'=>'close_bid_time', 'id'=>'close_bid', 'type' => 'text', 'class' => 'text tp' ); $data['descriptions'] = array( 'name'=>'descriptions', 'id'=>'descriptions', 'class' => 'text', 'rows' => 20, 'cols' => 30 ); return $data; } function edit_auction_model($id){ $auction = $this->get_auction_by_id($id); $data['image_file'] = array( 'name'=>'image_file', 'id'=>'image_file', 'type' => 'file', 'accept' => 'image/*', 'class' => 'text', 'onchange' => 'get_filename(this);' ); $data['file_name'] = array( 'name'=>'file_name', 'id'=>'file_name', 'type' => 'hidden', 'value' => $auction->image_path ); $data['fish_name'] = array( 'name'=>'fish_name', 'id'=>'fish_name', 'type' => 'text', 'class' => 'text', 'value' => $auction->fish_name ); $data['qty'] = array( 'name'=>'qty', 'id'=>'qty', 'type' => 'text', 'class' => 'text numeric', 'value' => $auction->qty ); $data['amount'] = array( 'name'=>'amount', 'id'=>'amount', 'type' => 'text', 'class' => 'text numeric', 'value' => $auction->amount ); $data['open_bid'] = array( 'name'=>'open_bid', 'id'=>'open_bid', 'type' => 'date', 'class' => 'text', 'value' => date('Y-m-d', strtotime($auction->open_bid)) ); $data['open_bid_time'] = array( 'name'=>'open_bid_time', 'id'=>'open_bid_time', 'type' => 'text', 'class' => 'text tp', 'value' => date('H:i:d', strtotime($auction->open_bid)) ); $data['close_bid'] = array( 'name'=>'close_bid', 'id'=>'close_bid', 'type' => 'date', 'class' => 'text', 'value' => date('Y-m-d', strtotime($auction->close_bid)) ); $data['close_bid_time'] = array( 'name'=>'close_bid_time', 'id'=>'close_bid_time', 'type' => 'text', 'class' => 'text tp', 'value' => date('H:i:d', strtotime($auction->close_bid)) ); $data['descriptions'] = array( 'name'=>'descriptions', 'id'=>'descriptions', 'class' => 'text', 'rows' => 20, 'cols' => 30, 'value' => $auction->description ); $data['image_name'] = $auction->image_name; return $data; } function bid_model($id, $userId) { $auction = $this->get_auction_by_id($id); $data['amount'] = array( 'name'=>'amount', 'id'=>'amount', 'type' => 'text', 'class' => 'text numeric', 'style' => 'display:inline;width:20%' ); $data['user_id'] = array( 'name'=>'user_id', 'id'=>'user_id', 'type' => 'hidden', 'value' => $userId ); $data['auction_id'] = array( 'name'=>'auction_id', 'id'=>'auction_id', 'type' => 'hidden', 'value' => $auction->auction_id ); $data['close_bid'] = array( 'name'=>'close_bid', 'id'=>'close_bid', 'type' => 'hidden', 'value' => $auction->close_bid ); $data['open_bid'] = array( 'name'=>'open_bid', 'id'=>'open_bid', 'type' => 'hidden', 'value' => $auction->open_bid ); return $data; } function tracking_model($id) { $tracking = $this->get_tracking($id); $data['awb_number'] = array( 'name'=>'amount', 'id'=>'amount', 'type' => 'text', 'class' => 'text', 'value' => $tracking->awb_number, 'readonly' => 'readonly' ); $data['origin'] = array( 'name'=>'origin', 'id'=>'origin', 'type' => 'text', 'class' => 'text', 'value' => $tracking->origin, ); $data['destination'] = array( 'name'=>'destination', 'id'=>'destination', 'class' => 'text', 'type' => 'text', 'value' => $tracking->destination, ); $data['date_of_shipment'] = array( 'name'=>'date_of_shipment', 'id'=>'date_of_shipment', 'type' => 'date', 'class' => 'text', 'value' => date('Y-m-d', strtotime($tracking->date_of_shipment)) ); $data['status'] = array( 'name'=>'status', 'id'=>'status', 'type' => 'text', 'class' => 'text', 'value' => $tracking->status, ); $data['tracking_id'] = array( 'name'=>'tracking_id', 'id'=>'tracking_id', 'type' => 'hidden', 'class' => 'text', 'value' => $tracking->tracking_id, ); return $data; } function get_tracking($id) { $this->db->where('auction_id',$id); return $this->db->get('tracking')->result()[0]; } function insert_auction() { $array = explode("\\",$this->input->post("file_name")); $image_name = $array[2]; $image_remove_space = str_replace(' ', '-', $image_name); // Replaces all spaces with hyphens. $config['file_name'] = $image_remove_space; $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config); $this->upload->initialize($config); if(!$this->upload->do_upload('image_file')) { return $this->upload->display_errors(); } else { $status = 'open'; $open_bid = strtotime($this->input->post('open_bid')); $close_bid = strtotime($this->input->post('close_bid')); $open_bid_combine = $this->input->post('open_bid').' '.$this->input->post('open_bid_time'); $close_bid_combine = $this->input->post('close_bid').' '.$this->input->post('close_bid_time'); $open_bid_date = strtotime($open_bid_combine); $close_bid_date = strtotime($close_bid_combine); if (now() >= $close_bid_date) { $status = 'closed'; } $image_upload = $this->upload->data('image_file'); $data_file= array( 'image_name' => $image_remove_space, 'image_path' => $this->upload->data()['full_path'], 'fish_name' => $this->input->post('fish_name'), 'amount' => $this->input->post('amount'), 'open_bid' => date('Y-m-d H:i:s',$open_bid_date), 'close_bid' => date('Y-m-d H:i:s',$close_bid_date), 'description' => $this->input->post('descriptions'), 'qty' => $this->input->post('qty'), 'status' => $status ); $this->db->insert('auction_data',$data_file); return 'success'; } } function get_auction_by_id($id) { $this->db->where('auction_id',$id); $query = $this->db->get('auction_data'); return $query->result()[0]; } function get_image_auction($id) { $this->db->where('auction_id',$id); $query = $this->db->get('auction_data'); return $query->result()[0]->image_path; } function save_auction($id) { $status = 'open'; $open_bid = strtotime($this->input->post('open_bid')); $close_bid = strtotime($this->input->post('close_bid')); $open_bid_combine = $this->input->post('open_bid').' '.$this->input->post('open_bid_time'); $close_bid_combine = $this->input->post('close_bid').' '.$this->input->post('close_bid_time'); $open_bid_date = strtotime($open_bid_combine); $close_bid_date = strtotime($close_bid_combine); if (now() >= $close_bid_date) { $status = 'closed'; } if ($this->input->post('file_name') != $this->get_image_auction($id)) { $array = explode("\\",$this->input->post("file_name")); $image_name = $array[2]; $image_remove_space = str_replace(' ', '-', $image_name); // Replaces all spaces with hyphens. $config['file_name'] = $image_remove_space; $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload', $config); $this->upload->initialize($config); if(!$this->upload->do_upload('image_file')) { return $this->upload->display_errors(); } else { $image_upload = $this->upload->data('image_file'); $data_file= array( 'image_name' => $image_name, 'image_path' => $this->upload->data()['full_path'], 'fish_name' => $this->input->post('fish_name'), 'amount' => $this->input->post('amount'), 'open_bid' => date('Y-m-d H:i:s',$open_bid_date), 'close_bid' => date('Y-m-d H:i:s',$close_bid_date), 'description' => $this->input->post('descriptions'), 'qty' => $this->input->post('qty'), 'status' => $status ); $this->db->where('auction_id',$id); $this->db->update('auction_data',$data_file); return 'success'; } } else{ $data_file= array( 'fish_name' => $this->input->post('fish_name'), 'amount' => $this->input->post('amount'), 'open_bid' => date('Y-m-d H:i:s',$open_bid_date), 'close_bid' => date('Y-m-d H:i:s',$close_bid_date), 'description' => $this->input->post('descriptions'), 'qty' => $this->input->post('qty'), 'status' => $status ); $this->db->where('auction_id',$id); $this->db->update('auction_data',$data_file); return 'success'; } } function get_all_auction() { $query = $this->db->get('auction_data'); $this->db->order_by('open_bid', 'desc'); return $query->result(); } function get_closed_auction() { $this->db->where('status','closed'); $this->db->order_by('open_bid', 'desc'); $this->db->join('users', 'users.id = auction_data.winner'); $query = $this->db->get('auction_data',5,0); return $query->result(); } function bid_now() { if (now() >= strtotime($this->input->post('close_bid'))) { $this->db->set('status', 'closed'); $this->db->where('auction_id', $this->input->post('auction_id')); $this->db->update('auction_data'); return 'closed'; } else if (now() < strtotime($this->input->post('open_bid'))) { return 'next'; } else{ $this->db->set('winner', $this->input->post('user_id')); $this->db->set('deal_amount', $this->input->post('amount')); $this->db->where('auction_id', $this->input->post('auction_id')); $this->db->update('auction_data'); return 'success'; } } function get_username($id) { $this->db->where('id',$id); return $this->db->get('users')->result()[0]->username; } function get_filename($id) { $this->db->where('auction_id',$id); return $this->db->get('auction_data')->result()[0]->image_name; } function get_open_auction() { $this->db->where('status', 'open'); $this->db->order_by('open_bid', 'desc'); $query = $this->db->get('auction_data'); return $query->result(); } function get_auction_page($limit,$offset) { $this->db->order_by('open_bid', 'desc'); $this->db->limit($limit,$offset); $query = $this->db->get('auction_data'); return $query->result(); } function delete_auction($id) { $this->db->where('auction_id', $id); $this->db->delete('auction_data'); } function get_for_check_payment() { $this->db->order_by('open_bid', 'desc'); $this->db->where('status', 'closed'); $this->db->where('status_payment', 0); $this->db->join('users', 'users.id = auction_data.winner'); $query = $this->db->get('auction_data'); return $query->result(); } function get_for_check_payment_page($limit, $offset) { $this->db->order_by('open_bid', 'desc'); $this->db->where('status', 'closed'); $this->db->where('status_payment', 0); $this->db->join('users', 'users.id = auction_data.winner'); $this->db->limit($limit,$offset); $query = $this->db->get('auction_data'); return $query->result(); } function update_payment($id) { $this->db->where('auction_id', $id); $this->db->set('status_payment', 1); $this->db->update('auction_data'); } function gettrackingnumber($id) { $resi = now().$id.rand(); $data_file= array( 'awb_number' => $resi, 'auction_id' => $id ); $this->db->insert('tracking',$data_file); return $resi; } function get_winner_email($id) { $this->db->where('auction_id',$id); $this->db->join('users', 'users.id = auction_data.winner'); return $this->db->get('auction_data')->result()[0]->email; } function checktrackingdb($id) { $this->db->where('auction_id',$id); return count($this->db->get('auction_data')->result()); } function get_for_check_tracking() { $this->db->order_by('open_bid', 'desc'); $this->db->where('status', 'closed'); $this->db->where('status_payment', 1); $this->db->join('users', 'users.id = auction_data.winner'); $query = $this->db->get('auction_data'); return $query->result(); } function get_for_check_tracking_page($limit, $offset) { $this->db->order_by('open_bid', 'desc'); $this->db->where('status', 'closed'); $this->db->where('status_payment', 1); $this->db->join('users', 'users.id = auction_data.winner'); $this->db->limit($limit,$offset); $query = $this->db->get('auction_data'); return $query->result(); } function tracking_update($id) { $data_file= array( 'origin' => $this->input->post('origin'), 'destination' => $this->input->post('destination'), 'date_of_shipment' => $this->input->post('date_of_shipment'), 'status' => $this->input->post('status'), ); $this->db->where('tracking_id',$id); $this->db->update('tracking',$data_file); } function tracking_search($id) { $this->db->where('awb_number',$id); return $this->db->get('tracking')->result()[0]; } function get_auction_top_four() { $this->db->order_by('open_bid', 'desc'); $this->db->where('status', 'open'); $this->db->limit(4,0); $query = $this->db->get('auction_data'); return $query->result(); } function check_current_price($id) { $this->db->where('auction_id',$id); $query = $this->db->get('auction_data'); return $query->result()[0]->deal_amount == '' ? 0 : $query->result()[0]->deal_amount; } }<file_sep><link rel="stylesheet" type="text/css" href="<?php echo base_url();?>assets/jquery-ui/jquery.timepicker.css"></script> <script src="<?php echo base_url();?>assets/jquery-ui/jquery.timepicker.js"></script> <h1>Edit Auction</h1> <?php echo form_open_multipart('admin/edit_auction/'.$auction_id);?> <div class="one-half"> <fieldset> <label>Fish Name <span class="required">*</span></label> <?php echo form_input($viewmodel['fish_name']); echo form_error('fish_name'); ?> </fieldset> <fieldset> <label>Qty (gr)<span class="required">*</span></label> <?php echo form_input($viewmodel['qty']); echo form_error('qty'); ?> </fieldset> <fieldset> <label>Price <span class="required">*</span></label> <?php echo form_input($viewmodel['amount']); echo form_error('amount'); ?> </fieldset> <fieldset> <label>Open bid date<span class="required">*</span></label> <?php echo form_input($viewmodel['open_bid']); echo form_input($viewmodel['open_bid_time']); echo form_error('open_bid'); ?> </fieldset> <fieldset> <label>Close bid date<span class="required">*</span></label> <?php echo form_input($viewmodel['close_bid']); echo form_input($viewmodel['close_bid_time']); echo form_error('close_bid'); ?> </fieldset> </div> <div class="one-half last"> <fieldset> <img src=<?php echo base_url().'uploads/'.$viewmodel['image_name']?> width="100px"> </fieldset> <fieldset> <label>Change Image</label> <?php echo form_upload($viewmodel['image_file']); if (form_error('file_name') == '') { echo $error_upload; } else{ echo form_error('file_name'); } echo form_input($viewmodel['file_name']); ?> </fieldset> <fieldset> <label>Description <span class="required">*</span></label> <?php echo form_textarea($viewmodel['descriptions']); echo form_error('descriptions'); ?> </fieldset> </div> <div style="clear:both; height: 40px;"> <fieldset> <input name="Mysubmitted" id="Mysubmitted" value="Save" class="button white button-submit" type="submit"> </fieldset> </div> </form> <!--END form ID contact_form --> <script type="text/javascript"> $('.numeric').blur(function(){ var input = parseFloat($(this).val()).toFixed(1); $(this).val(input); }); $(document).ready(function(){ $('.tp').timepicker({ timeFormat: 'HH:mm:ss' }); }); </script><file_sep><h1><?php echo lang('create_user_heading');?></h1> <p><?php echo lang('create_user_subheading');?></p> <div class="one-half"> <?php echo form_open("auth/register");?> <fieldset> <?php echo lang('create_user_fname_label', 'first_name');?><span class="required">*</span> <?php echo form_input($first_name)?> <?php echo form_error('first_name')?> </fieldset> <fieldset> <?php echo lang('create_user_lname_label', 'last_name');?><span class="required">*</span> <?php echo form_input($last_name);?> <?php echo form_error('last_name')?> </fieldset> <fieldset> <label>User Category <span class="required">*</span></label> <?php $attribute = array('class' => 'text', 'onchange' => 'categoryChange(this)' ); ?> <?php echo form_dropdown('category',$category,'',$attribute);?> </fieldset> <fieldset class="company-name" style="display:none"> <?php echo lang('create_user_company_label', 'company');?> <?php echo form_input($company);?> </fieldset> <fieldset> <?php echo lang('create_user_email_label', 'email');?><span class="required">*</span> <?php echo form_input($email);?> <?php echo form_error('email')?> </fieldset> <fieldset> <?php echo lang('create_user_phone_label', 'phone');?><span class="required">*</span> <?php echo form_input($phone);?> <?php echo form_error('phone')?> </fieldset> </div> <div class="one-half last"> <fieldset> <?php echo lang('create_user_password_label', 'password');?><span class="required">*</span> <?php echo form_input($password);?> <?php echo form_error('password')?> </fieldset> <fieldset> <?php echo lang('create_user_password_confirm_label', 'password_confirm');?><span class="required">*</span> <?php echo form_input($password_confirm);?> <?php echo form_error('password_confirm')?> </fieldset> <fieldset> <label>NPWP <span class="required">*</span></label> <?php echo form_input($npwp);?> <?php echo form_error('npwp')?> </fieldset> <fieldset> <label>Address <span class="required">*</span></label> <?php echo form_textarea($address);?> <?php echo form_error('address')?> </fieldset> </div> <div style="clear:both; height: 40px;"> <fieldset> <input name="Mysubmitted" id="Mysubmitted" value="Register" class="button white button-submit" type="submit"> </fieldset> </div> <?php echo form_close();?> <script type="text/javascript"> function categoryChange(val){ if ($(val).val() == 'Company'){ $('.company-name').show(); } else{ $('.company-name').hide(); } } </script><file_sep> <!-- tab panes --> <div id="prod_wrapper"> <div id="panes"> <?php foreach ($auction as $key ) { ?> <div> <img src="<?php echo base_url()."uploads/".$key->image_name?>" alt="" width="379px" height="225px"> <h5>Sold</h5> <p style="color:#2997AB;">Winner <br/> <?php echo $key->username.' - Rp '.$key->deal_amount; ?></p> <p> Fish Name : <?php echo $key->fish_name; ?> <br/>Price : Rp <?php echo $key->amount; ?> <br/>Qty : <?php echo $key->qty; ?> gr</p> <p><?php echo $key->description; ?></p> </div> <?php } ?> </div> <!-- END tab panes --> <br clear="all"> <!-- navigator --> <div id="prod_nav"> <ul> <?php $id = 1; foreach ($auction as $key ) { if ($id % 6 == 0) { ?> </ul><ul> <?php } $image_name_split = explode(".",$key->image_name); ?> <li><a href="#<?php echo $image_name_split[0]; ?>"><img src="<?php echo base_url()."uploads/".$key->image_name?>" alt="" height="75px" width="75px"><strong>Class aptent</strong>Rp <?php echo $key->amount ?></a></li> <?php $id++; } ?> </ul> </div> <!-- close navigator --> </div> <!-- END prod wrapper --> <div style="clear:both"></div> <h1 style="padding: 20px 0">This is what we do</h1> <blockquote>Nulla hendrerit commodo tortor, vitae elementum magna convallis nec. Nam tempor nibh a purus aliquam et adipiscing elit gravida. Ut vitae nunc a libero volutpat gravida. Nullam egestas mi sit amet dui scelerisque eu laoreet nisi ultrices. Ut vitae nunc a libero volutpat gravida. Nam tempor nibh a purus aliquam. </blockquote> <p style="text-align:right; margin-right: 16px; margin-bottom: 15px"><a href="<?php echo base_url(); ?>index.php/landing/live_auction" class="button" style="font-size: 18px">More Auction</a></p> <!-- First Column --> <ul class="ca-menu" style="margin: 40px 0"> <?php foreach ($auctiontopfour as $key ) { ?> <li style="margin-top:15px"> <a href="#"> <span class="ca-icon"><img src="<?php echo base_url()."uploads/".$key->image_name;?>" width="230px" height="200px"></span> <div class="ca-content"> <input type="hidden" name="auction_id" value="<?php echo $key->auction_id;?>"> <h2 class="ca-main" style="margin:0"><button class="button-bid" type="button" onclick="bidNow(this);">Bid Now</button></h2> <h3 class="ca-sub">Rp <?php echo $key->amount; ?></h3> </div> </a> </li> <?php } ?> </ul> <div style="clear:both; height: 40px"></div> <script> function bidNow(val) { var base_url = '<?php echo base_url(); ?>'; var login = <?php echo $login; ?>; if (login != 1) { alert('Please Log In to Your Account'); } else{ window.location.href = base_url + 'index.php/auction/detail/' + $(val).parent().prev().val(); } } </script>
f4e64416c51deecb41a856552f86042fa7fad918
[ "PHP" ]
17
PHP
Hanifah/e-fishauction
cdbad0ced1688361790fddd7f02591a4000822b2
0f8e70167c70d15c4c2253de8c51872b9a63650f
refs/heads/master
<repo_name>wilson428/labelify<file_sep>/README.md labelify.js 0.1a ======== # DESCRIPTION Raphael-powered labeler for jQuery sliders. By calling labelify() on the slider element's ID, this instutes tick marks and label using Raphael silently--meaning it creates its own paper instance and doesn't require the developer to mess with any Raphael calls. # DEPENDENCIES jQuery jQuery UI [Raphael.js](https://raw.github.com/DmitryBaranovskiy/raphael/master/raphael.js) After a slider is instantiated, feed its ID to the function like so: labelify("#timeslider"); While it would make sense to add a "labelify(this)" line to the create() function, I believe the slider's events are not all initiated. Labelify needs those events so that clicking the labels calls the correct behavior. # TO DO - Move styling to a CSS file - Determine the offset in labels -- currently a crude "- 10" (line 29) -- dynamically<file_sep>/src/labelify.js //Draw ticks on a jQ slider with Raphael /*global Raphael*/ function labelify(slider_id) { if (!slider_id) { return; } var slider_obj = $(slider_id).css({ margin: '0px auto', position: 'absolute', bottom: 18, left: 0, right: 0 }), container = $("<div />", { id: slider_id + "_container" }).css({ position: 'relative', width: slider_obj.width() + 20, height: '75px' }); //wrap label in container and put label canvas on top of it slider_obj.wrap(container); var spaper = Raphael(slider_id + '_container', container.width(), container.height()); var min = slider_obj.slider("option", "min"), max = slider_obj.slider("option", "max"), step = slider_obj.slider("option", "step"), slider_x = slider_obj.position().left + slider_obj.offset().left - 10, slider_y = slider_obj.position().top, n = (max - min) / step, w = slider_obj.width() / n, ticks = spaper.set(), labels = spaper.set(); //draw ticks and set click event for labels for (var c = 0; c <= n; c += 1) { var x = slider_x + c * w, tick = spaper.path("M" + x + "," + slider_y + "L" + x + "," + (slider_y - 4)).attr({ "stroke" : "#666", "stroke-width" : 1 }), label = spaper.text(x, slider_y - 18, String(min + step * c)).attr({ "text-anchor" : "middle", "fill" : "#666", "cursor" : "pointer" }).transform("r-90"); ticks.push(tick); labels.push(label); } labels.click(function(e) { slider_obj.slider("option", "value", parseInt(this.attr("text"), 10)); slider_obj.trigger("slide"); }); }
0b4fe99c5e23f166381ea8486dfbd81f6c01f9de
[ "Markdown", "JavaScript" ]
2
Markdown
wilson428/labelify
e119be8472f9c2297fab5b5cea4050479f333226
1944b550442b72c190ca0f352d26b37b8437ad79
refs/heads/master
<repo_name>mrahman1/my-select-web-100817<file_sep>/lib/my_select.rb def my_select(collection) i = 0 selection = [] while i < collection.length if yield(collection[i]) selection.push(collection[i]) end i=i+1 end return selection end
9894d7fa1e97a3f956c70659349466472aa40905
[ "Ruby" ]
1
Ruby
mrahman1/my-select-web-100817
a95697c82847dabb71d41a78ac736f292da26be5
0fcde055acabc6c85a7cad249862d8b69fad7d7c
refs/heads/master
<file_sep>#ifndef ARBOL_B_H #define ARBOL_B_H #include <cstddef> #include <iostream> #include <cstdlib> ///COMPLETAR ESTA CLASE TEMPLATE Y PROBARLA CON ENTEROS, LUEGO PASAR A PROBARLA CON ESTRUCTURAS QUE ///TENGAN SOBRECARGADO EL OPERADOR < ... using namespace std; template <typename T> struct nodo{ //Revisar si es necesario que este constituida como una clase, o si es suficiente que sea un Struct... T p; nodo<T>* father; nodo<T>* left; nodo<T>* right; // int operator<<(nodo<T> Q){ // return 0; // } }; //Este arbol va a ser usado con Event_Points y con Segmentos, asi que ambas deberan tener sobregarcada la "Operacion <", //el arbol la empleara como funcion fundamental para le balanceo, la insercion, el borrado y la busqueda. //Estructura de Arbol Balanceado AVL, resolver situacion para los segmentos(requiera para su ordenamiento la altura de la sweep line) //revisar el template //Para ser usada, tanto para la estrctura Q, que maneja puntos de Eventos, como para la estructura T, qeu controla el estado de la sweep_line. //En casod e complejisarse, se pueden crear 2 estructuras arbol separadas, únicas o usar Set para Q como se uso antes. template<class T> class Arbol_B { private: nodo<T>* raiz; nodo<T>* actual; public: ///ARREGLAR LA CLASE ARBOL!!!!! Arbol_B(); //Ya se realiza una correcta insercion y balanceo... void Insert(T ep); //REVISAR SI NO SERIA NECESARIO RETORNAR EL AGREGADO... nodo<T>* Insert(T ep, nodo<T>* act); void Delete(T ep); nodo<T>* Delete(T ep, nodo<T>* act); nodo<T>* Find(T ep); //para buscar un elemento determinado en el arbol.Util para el Delete nodo<T>* Find(T ep, nodo<T>* act); //El mas izquierdo a partir de un nodo nodo<T>* leftmost(nodo<T>* l); //El mas derecho a partir de un nodo nodo<T>* rightmost(nodo<T>* r); nodo<T>* rotate_left(nodo<T>* root); nodo<T>* rotate_right(nodo<T>* root); //realiza el balance del arbol, para arbol AVL, chequeo la altura por izuqierda y por derecha, si difiere, debo realizar un giro en ese sentido. nodo<T>* balance(nodo<T>* P); bool empty(); nodo<T>* begin(); ///Para mostrar el arbol al testear... void show(); void show(nodo<T>* act, int nivel); ~Arbol_B(); }; #endif <file_sep>#include "Arbol_B.h" #include "Estructuras.h" using namespace std; template<class T> Arbol_B<T>::Arbol_B() { raiz = NULL; actual = raiz; } template<class T> Arbol_B<T>::~Arbol_B() { } //------------------------------------------------------------------------------ ///Inserta el nodo a partir de la raiz, para insertarlo correctamente a izquierda o derecha, segun corresponda, ///y realizar el balanceo... template<class T> void Arbol_B<T>::Insert (T ep) { raiz = Insert(ep, raiz); } ///Operacion de insercion recursiva, al encontrar una hoja en NULL, inserta alli el nodo correspondiente... template<class T> nodo<T>* Arbol_B<T>::Insert (T ep, nodo<T>* act) { if(!act){ //Cuando act = NULL, el ! cambia la evalucaion de la expresion de falso a verdadero... act = new nodo<T>; act->p = ep; act->left = NULL; act->right = NULL; return act; } ///Si no era nulo, revisa si va a izquierda o derecha, y realiza recursion... if(ep<act->p){ ///se cambia el nuevo hijo, no cambiara salvo que haya sido NULL, o se haya realizado balanceo... act->left = Insert(ep, act->left); } else{ ///se cambia el nuevo hijo, no cambiara salvo que haya sido NULL, o se haya realizado balanceo... act->right = Insert(ep, act->right); } return balance(act); } //------------------------------------------------------------------------------ //Se supone que el nodo que quiero borrar esta si o si en el arbol. template<class T> void Arbol_B<T>::Delete(T ep){ raiz = Delete(ep, raiz); } template<class T> nodo<T>* Arbol_B<T>::Delete (T ep, nodo<T>* act) { //Voy a hacer la misma busqueda en el Delete, pero aprovecho el mecanismo para //controlar el factor de balanceo de los nodos. if(!act) return NULL; if(ep == act->p){ nodo<T>* aux; if(act->left!=NULL){ aux = rightmost(act->left); act->p=aux->p; act->left = Delete(aux->p,act->left); } else{ if(act->right!=NULL){ aux = leftmost(act->right); act->p=aux->p; act->right = Delete(aux->p,act->right); } else{ //free(act); return NULL; } } } else{ if(ep<act->p){ if(!act->left){ cout<<"NULL LEFT SIN"<<endl; cout<<"---------------------------------------------------------"<<endl; cout<<"SEGMENTO: "<<endl; ep.show(); cout<<endl; cout<<"ARBOL T: "<<endl; show(); cout<<"---------------------------------------------------------"<<endl; system("pause"); } act->left = Delete(ep,act->left); } else{ if(!act->right){ cout<<"NULL RIGHT SIN"<<endl; cout<<"---------------------------------------------------------"<<endl; cout<<"SEGMENTO: "<<endl; ep.show(); cout<<"ARBOL T: "<<endl; show(); cout<<"---------------------------------------------------------"<<endl; system("pause"); } act->right = Delete(ep,act->right); } } return balance(act); } //------------------------------------------------------------------------------ template<class T> nodo<T> * Arbol_B<T>::leftmost (nodo<T> * l) { if(l->left==NULL){ return l; } return leftmost(l->left); } template<class T> nodo<T> * Arbol_B<T>::rightmost (nodo<T> * r) { if(r->right==NULL){ return r; } return rightmost(r->right); } //------------------------------------------------------------------------------ template<class T> nodo<T>* Arbol_B<T>::Find (T ep) { return Find(ep,raiz); } template<class T> nodo<T>* Arbol_B<T>::Find (T ep, nodo<T>* act) { if(act == NULL) return NULL; if(ep == act->p) return act; if(ep<act->p){ return Find(ep,act->left); } else{ return Find(ep,act->right); } } //------------------------------------------------------------------------------ template<class T> nodo<T>* Arbol_B<T>::rotate_left (nodo<T>* root) { nodo<T>* P=root->right; if(P){ root->right=P->left; if(P->left){ P->left->father=root; } P->left=root; } return P; } template<class T> nodo<T>* Arbol_B<T>::rotate_right (nodo<T>* root) { nodo<T>* P=root->left; if(P){ root->left=P->right; if(P->right!=NULL){ P->right->father=root; } P->right=root; } return P; } template<class T> //N es el nodo al cual se le inserto un nodo, P es su padre, de este modo considero de a //2 elementos para hacer los rotate nodo<T>* Arbol_B<T>::balance(nodo<T>* P) { // si es -2 indica que hay de mas a la izquierda if (calc_factor(P) == -2) { if (calc_factor(P->left) == 1) { P->left = rotate_left(P->left); } return rotate_right(P); } else{ if (calc_factor(P) == 2) { if (calc_factor(P->right) == -1) { P->right = rotate_right(P->right); } return rotate_left(P); } } return P; } //------------------------------------------------------------------------------ //Funciones Auxiliares Extras template<class T> int calc_nivel(nodo<T>* act){ if(!act){ return 0; } int nivel = 1; nivel += max(calc_nivel(act->left),calc_nivel(act->right)); return nivel; } template<class T> int calc_factor(nodo<T>* act){ int factor = 0; factor = 0; factor += (act->right)? calc_nivel(act->right): 0; factor -= (act->left)? calc_nivel(act->left) : 0; return factor; } //------------------------------------------------------------------------------ template<class T> void Arbol_B<T>::show(){ show(raiz,0); } template<class T> void Arbol_B<T>::show (nodo<T>* act, int nivel) { int aux = nivel+1; if(!act) return; if(act->left){ show(act->left,aux); } cout<<"Nivel: "<<nivel<<endl; // cout<<act->p<<" "; //SOLO PARA TESTEO, ELIMINAR LUEGO... act->p.show(); //cout<<"Balance Factor: "<<act->balance_factor<<endl; cout <<endl; if(act->right){ show(act->right,aux); } } template<class T> bool Arbol_B<T>::empty ( ) { return !raiz; } template<class T> nodo<T>* Arbol_B<T>::begin ( ) { return raiz; } ///NECESARIO PARA EL FUNCIONAMIENTO, DEFINIR AQUI EN QUE TIPOS SE PODRA EMPLEAR EL ARBOL... //template class Arbol_B<int>; template class Arbol_B<segmento>; template class Arbol_B<event_point>; <file_sep>#ifndef ESTRUCTURAS_H #define ESTRUCTURAS_H #include <iostream> #include <vector> #include <list> #include <deque> #include <cmath> using namespace std; struct vertex; struct halfedge; struct face; //------------------------------------------------------------------------------------------------------------ struct punto{ double x; double y; //orden lexicografico para la distincion, mayor y, va a la izquierda, mismo y, //si x es menor va a la izquierda, en otro caso, va a la derecha. bool operator<(punto P){ bool menor = false; double error = 1e-8; //Este colocara los mas altos e izquierdos, ala izquierda del arbol para //obtener el siguiente evento, buscando el leftmost(mas izquierdo) del arbol... if(this->y > P.y + error) menor = true; if(fabs(this->y - P.y)<= error){ if(this->x < P.x - error){ menor = true; } } return menor; } bool operator==(punto P){ double error = 1e-8; return fabs(this->x - P.x) <= error && fabs(this->y - P.y) <= error; } }; struct segmento{ punto ini; punto fin; ///Guarda una referencia a una de las media aristas que representan el segmento, empleada para la ///construccion del grafo, guardara la media arista por debajo de la sweep_line. halfedge* arista; ///Referencia a la altura de la SWEEP_LINE en la clase INTERSECCION, de modo que puedan conocer /// la altura de la misma cuando deban realizar las operaciones de comparacion double* y; double get_x(double altura){ if(ini.x==fin.x){ return ini.x; } double delta_x, delta_y, m, b, X; //Considerando la ecuacion de la recta: // y = m * x + b; Siendo m la pendiente de la recta, y b su coordenada de origen. //Deduzco a partir de los puntos conocidos inicial y final la pendiente //y ordenada de origen, luego reemplazo por la altura buscada y calculo la x. delta_x = ini.x - fin.x; //Se caga para segmentos veritcales, arreblar... delta_y = ini.y - fin.y; ///Pendiente m = delta_y/delta_x; ///Coordenada de Origen b= fin.y - m*fin.x; ///Calculo de X a partir de un Y conocido. // (y - b) / m = x; X = (altura - b) / m; return X; } //Para testearlo lo ponemos en esta forma simplificada... //bool operator<(segmento Q, double altura){ bool operator<(segmento Q){ ///ARREGLADO PARCIAL, EL BIAS DEL ERROR ME ESTABA PROVOCANDO PROBLEMAS, REVISAR PORQUE... double error = 1e-15; double altura = *y; double A = get_x(altura); double C = Q.get_x(altura); if(C < A-error){ return true; } else{ if(C > A+error){ return false; } else{ A = get_x(altura-1); C = Q.get_x(altura-1); if(C < A - error) return true; else return false; } } } bool contains(punto p){ bool cont; double error = 1e-8; double denom = fin.x-ini.x; double alpha, suma; if(!denom){ alpha = (p.y-ini.y)/(fin.y - ini.y); suma = (1-alpha)*ini.x + (alpha)*fin.x; cont = fabs(suma - p.x) <= error && alpha>0 && alpha<1; } else{ alpha = (p.x-ini.x)/denom; suma = (1-alpha)*ini.y + (alpha)*fin.y; cont = fabs(suma - p.y )<= error && alpha>0 && alpha<1; } return cont; } bool operator==(segmento Q){ return (this->ini==Q.ini && this->fin==Q.fin); } void show(){ cout<< "Segmento: X: "<< this->get_x(*this->y)<<" Y: "<<*this->y<<endl; } }; struct event_point{ punto p; ///Coordenada del punto. vector<segmento> U; ///Conjuntos de INDICES de los segmentos que comienzan en ese punto. vertex* vertice; bool operator<(event_point P){ return this->p<P.p; } bool operator==(event_point P){ return this->p==P.p; } void show(){ cout<< "Punto de Evento: X: "<< this->p.x <<" Y: "<<this->p.y<<endl; } }; //------------------------------------------------------------------------------------------------------------ struct vertex{ punto p; halfedge* incidente; vector<halfedge*> incidentes; void add_halfedge(halfedge *he) { incidentes.push_back(he); } }; struct halfedge{ vertex* origen; face* incidente; halfedge* gemela; halfedge* anterior; halfedge* siguiente; }; struct face{ halfedge* exterior; list<halfedge*> f_interior; }; //------------------------------------------------------------------------------------------------------------ struct Grafos{ deque<vertex> vertice; deque<halfedge> arista; deque<face> cara; //siempre deberia comenzar con 1 elemento, por la cara exterior al infinito. }; //------------------------------------------------------------------------------------------------------------ #endif <file_sep>#ifndef INTERSECCION_H #define INTERSECCION_H #include <vector> #include "Arbol_B.h" #include "Estructuras.h" #include <cmath> using namespace std; ///Dado un conjunto de puntos y los segmentos formados por esos puntos, construyo el grafo correspondiente ///aplicando el algoritmo de interseccion de la Sweep Line visto en clase. class Interseccion { private: vector<punto> intersecciones; ///Vector que almacena los puntos resultantes de las intersecciones double sweep_line; ///Altura de la Sweep Line /*Cola de Eventos*/ Arbol_B<event_point> Q; /*Arbol de Estado*/ Arbol_B<segmento> T; Grafos grafo; ///Grafo final formado por los segmentos. public: Interseccion(); Grafos grafo_resultante(); ///Devuelve finalmente el grafo resultante del conjunto de segmentos. void InitializeQ(vector<segmento> S); void FindIntersection( vector<segmento> S ); void HandleEventPoint(event_point p); void findNewEvent(segmento sl, segmento sr, event_point p); bool calc_inter(segmento s1, segmento s2, event_point &p); void FindNeighbors( nodo<segmento>* &sl, nodo<segmento>* &sr, segmento p, nodo<segmento>* act); segmento LeftmostSegment(vector<segmento> mayor, vector<segmento> menor); segmento RightmostSegment(vector<segmento> mayor, vector<segmento> menor); vector<punto> GetIntersection(); ~Interseccion(); }; #endif <file_sep>#include "Interseccion.h" Interseccion::Interseccion() { } Interseccion::~Interseccion() { } Grafos Interseccion::grafo_resultante ( ) { } ///MEDIDA DEL ERROR: 0.000000005; ///AL PRINCIPIO CUANDO SETEO LOS SEGMENTOS, DEBO HACER QUE SU CAMPO (*Y) APUNTE AL DOUBLE SWEEP_LINE /// DE LA CLASE, DE ESTE MODO LO UNICO QUE TENGO QUE HACER LUEGO ES CAMBIAR SWEEP_LINE CUANDO LO NECESITE /// Y NO VOLVER A TOCAR EL CAMPO (*Y). ///COMO (*Y) APUNTA A LA DIRECCION DOUBLE SWEEP_LINE, AL CAMBIAR EL VALOR DE SWEEP_LINE, NO CAMBIA ///SU DIRECCION, CON LO CUAL (*Y) SIEMPRE SE MANTIENE ACTUALIZADA CON EL ULTIMO VALOR DE LA SWEEP_LINE. void Interseccion::FindIntersection (vector<segmento> S ) { ///1) Inicializar Q el arbol que contendra los event_point InitializeQ(S); ///2) Inicializar el arbol de estados T... event_point aux; //Q.show(); while(!Q.empty()){ aux = Q.leftmost(Q.begin())->p; HandleEventPoint(aux); Q.Delete(aux); //cout<<"----------------------------------------------------------"<<endl; //Q.show(); } } ///AGREGAR FIND_LC A INTERSECCION...LO MISMO PARA LAS QUE SON EXTRA EN ARBOL...ELIMINAR LEFT Y RIGHT DE ARBOL_B void find_LC(event_point ep, vector<segmento> &L, vector<segmento> &C, nodo<segmento>* n){ if(!n) return; find_LC (ep,L,C,n->left); if(n->p.fin == ep.p){ L.push_back(n->p); } else{ if(n->p.contains(ep.p)){ C.push_back(n->p); } } find_LC (ep,L,C,n->right); } ///LO SIGUIENTES PASOS NO CONTEMPLAN UNA RECTA HORIZONTAL, REVISAR Y ARREGLAR... void Interseccion::HandleEventPoint (event_point ep) { ///------------------------------------------------------------------------------------------------------ ///Paso 1: Encontrar los segmentos en T que terminan o contienen al evento 'p', los que incian con 'p' /// se encuentran almacenados en el mismo event_point. vector<segmento> L, C; ///PROBLEMAS: NO ENCUENTRA LA INTERSECCION, NO DEVUELVE CORRECTAMENTE LOS VECTORES... find_LC(ep,L,C,T.begin()); int nU = ep.U.size(); int nL = L.size(); int nC = C.size(); int nI = nU + nL + nC; ///------------------------------------------------------------------------------------------------------ ///Paso 2: Si existe mas de un segmento que comienza, contiene, o termina con este punto de evento, es una /// interseccion de varios segmentos y se lo trata correctamente. if(nI > 1){ //REVISAR LA INTEGRACION DE ESTAS COSAS CON EL GRAFO.... ///En los conjuntos U,C y L se poseen todos los segmentos que se intersectan en este punto de evento, ///en cuanto a la integracion del grafo, en este punto puedo tomar todos estos segmentos y realizar /// los procedimientos necesario para actualizar el grafo. ///Para el caso de los segmentos en C, se deberan crear 2 halfedge nuevos, enlazarlos correctamente, y corregir ///los NEXT y PREV como corresponda, debido a esto, los segmentos en C deberian ser los primeros en tratarse, ///REVISAR!... ///Para el caso de los segmentos en U y L solo se requerira cambiar los NEXT y PREV. intersecciones.push_back(ep.p); } ///------------------------------------------------------------------------------------------------------ ///Paso 3: Eliminar todos los segmentos que terminan o contienen al evento del arbol de estado, en el caso /// de los segmentos que contienen al evento, su eliminacion y reinsercion. ///Altura de la sweep_line, para hacer la busqueda para eliminacion necesito pasarle la altura a los ///segmentos, para evitar problemas al ser punto de interseccion, elevo la sweep_line un poco, con lo ///cual evito que recorra de manera equivocada el arbol al comparar empleando el operador '<'. sweep_line = ep.p.y; ///NO ESTA HACIENDO MAL LOS DELETE, EL PROBLEMA ESTA EN QUE AL NO COMPUTARSE LA INTERSECCION SE MUEVE MAL ///POR EL ARBOL, COMPLETAR LA INTERSECCION... if(nC > 1) sweep_line += 1e-9; for(int i=0;i<nL;i++){ T.Delete(L[i]); } for(int i=0;i<nC;i++){ // cout<<"---------------------------------------------------------"<<endl; // cout<<"ARBOL T: "<<endl; // T.show(); // cout<<"---------------------------------------------------------"<<endl; // T.Delete(C[i]); // cout<<"---------------------------------------------------------"<<endl; // cout<<"ARBOL T: "<<endl; // T.show(); // cout<<"---------------------------------------------------------"<<endl; } ///------------------------------------------------------------------------------------------------------ ///Paso 4: Insertar todos los segmentos que comienzan en el evento, los cuales estaran almacenados en el /// event_point mismo, y reinsertar todos los segmentos que pertenecen al conjunto C, para su reinsercion /// se concidera una altura por debajo de la sweep_line, asi evaluara la posicion de los segemtos justo /// despues de la interseccion. ///EL ERROR ESTABA ACA, SI BAJO O SUBO MUCHO LA sweep_line CON RESPECTO A LOS PUNTOS QUE SE INTERSECTAN, /// ALTERO EL ORDEN COMPLETO DEL ARBOL, SE LO DEBE MANEJAR CON CUIDADO COMO AL ERROR... if(nC > 1) sweep_line -= 2*1e-9; for(int i=0;i<nU;i++){ T.Insert( ep.U[i] ); } for(int i=0;i<nC;i++){ // cout<<"---------------------------------------------------------"<<endl; // cout<<"ARBOL T: "<<endl; // T.show(); // cout<<"---------------------------------------------------------"<<endl; // T.Insert(C[i]); // cout<<"---------------------------------------------------------"<<endl; // cout<<"ARBOL T: "<<endl; // T.show(); // cout<<"---------------------------------------------------------"<<endl; } //if(nC > 1) sweep_line += 0.000000005; ///------------------------------------------------------------------------------------------------------ ///Paso 5: Insertar todos los segmentos que comienzan en el evento, los cuales estaran almacenados en el /// event_point mismo, y reinsertar todos los segmentos que pertenecen al conjunto C, para su reinsercion nodo<segmento>* sl = NULL; nodo<segmento>* sr = NULL; if( nU + nC == 0){ for(int i =0;i<nL;i++){ FindNeighbors(sl,sr,L[i], T.begin()); if(sl && sr){ findNewEvent(sl->p,sr->p,ep); } } } else{ segmento sI,sD; /// sI = segmento mas iaquierdo entre U y C, sL = segmento mas derecho entre U y C. //Crear estas funciones... if(ep.U.size()<C.size()){ sI = LeftmostSegment(C, ep.U); sD = RightmostSegment(C, ep.U); } else{ sI = LeftmostSegment(ep.U, C); sD = RightmostSegment(ep.U, C); } FindNeighbors(sl,sr,sI, T.begin()); ///ARREGLAR ESTA SECCION... if(sl){ findNewEvent(sl->p,sI,ep); } sl = NULL; sr = NULL; FindNeighbors(sl,sr,sD, T.begin()); if(sr){ findNewEvent(sr->p,sD,ep); } } } void Interseccion::FindNeighbors( nodo<segmento>* &sl, nodo<segmento>* &sr, segmento p, nodo<segmento>* act){ if(!act) return; if(p == act->p){ if(act->left){ sl = T.rightmost(act->left); } if(act->right){ sr = T.leftmost(act->right); } return; } if(p<act->p){ sr = act; FindNeighbors(sl,sr,p,act->left); } else{ sl = act; FindNeighbors(sl,sr,p,act->right); } } void Interseccion::findNewEvent (segmento sl, segmento sr, event_point ep) { event_point inter; if(calc_inter(sl,sr, inter)){ if(inter.p.y < ep.p.y && !Q.Find(inter)){ Q.Insert(inter); } } } double producto_cruz(punto A, punto B, punto C){ //segmento AB(b-a), y segmento AC(c-a) return (B.x - A.x)*(C.y - A.y) - (C.x - A.x)*(B.y - A.y); } bool Interseccion::calc_inter (segmento s1, segmento s2, event_point &ep) { ///Segmento P punto A = s1.ini; punto B = s1.fin; ///Segmento Q punto C = s2.ini; punto D = s2.fin; double ABC,ABD,CDA,CDB; double a; ABC = producto_cruz(A,B,C); ///Vector AB (A---->B) = B-A ABD = producto_cruz(A,B,D); CDA = producto_cruz(C,D,A); ///Vector CD (C---->D) = D-C CDB = producto_cruz(C,D,B); if(ABC*ABD > 0){ return false; } if(CDA*CDB > 0){ return false; } if(fabs(ABD-ABC)<fabs(CDB-CDA)){ a = (0-ABC)/(ABD-ABC); ep.p.y = C.y*(1-a)+D.y*a; ep.p.x = C.x*(1-a)+D.x*a; } else{ a = (0-CDA)/(CDB-CDA); ep.p.y = A.y*(1-a)+B.y*a; ep.p.x = A.x*(1-a)+B.x*a; } return true; } segmento Interseccion::LeftmostSegment(vector<segmento> mayor, vector<segmento> menor){ int n = mayor.size(); int m = menor.size(); segmento leftmost = mayor[0]; for (int i=1;i<n;i++){ if(mayor[i]< leftmost){ leftmost = mayor[i]; } if(n<m){ if(menor[i]<leftmost){ leftmost = menor[i]; } } } return leftmost; } segmento Interseccion::RightmostSegment(vector<segmento> mayor, vector<segmento> menor){ int n = mayor.size(); int m = menor.size(); segmento rightmost = mayor[0]; for (int i=1;i<n;i++){ if(rightmost<mayor[i]){ rightmost = mayor[i]; } if(n<m){ if(rightmost<menor[i]){ rightmost = menor[i]; } } } return rightmost; } void Interseccion::InitializeQ(vector<segmento> S){ event_point evI, evF; ///Agregar los puntos de los segmentos en S como puntos de evento en Q int n = S.size(); for (int i=0; i<n;i++){ //GraphConverter(S[i]); S[i].y = &sweep_line; ///Como las aristas siempre se insertan al final, hago uso de eso ///para asignar los halfedge correspondientes a cada segmento. //Seņala a la arista izquierda, la que corresponderia al interior, puedo moverme a //cualquiera haciendo uso de la gemela. //S[i].halfEdge = grafo.arista.size()-1; evI.p = S[i].ini; evI.U.push_back(S[i]); evF.p = S[i].fin; nodo<event_point>* n_aux = Q.Find(evI); if(!n_aux){ Q.Insert(evI); } else{ n_aux->p.U.push_back(S[i]); } n_aux = Q.Find(evF); if(!n_aux){ Q.Insert(evF); } evI.U.clear(); } } vector<punto> Interseccion::GetIntersection(){ return intersecciones; } <file_sep>#include <GL/glut.h> #include <iostream> #include <iomanip> #include "Arbol_B.h" #include "Interseccion.h" #include <ctime> using namespace std; vector<segmento> S; vector<punto> I; bool hecho = false; segmento Get_Segment(){ punto a,b; segmento seg; ///Crea punto scon una precision de hasta 4 decimales... a.x = (rand()%101); a.y = (rand()%101); b.x = (rand()%101); b.y = (rand()%101); if(b.y > a.y){ seg.ini=b; seg.fin=a; } else{ if(b.y < a.y){ seg.ini=a; seg.fin=b; } else{ ///CASO CUANDO ES HORIZONTAL, TODAVIA NO CONTEMPLADO... b.y-=1; seg.ini=a; seg.fin=b; } } return seg; } void reshape_cb (int w, int h) { if (w==0||h==0) return; glViewport(0,0,w,h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluOrtho2D(0,100,0,100); glMatrixMode (GL_MODELVIEW); glLoadIdentity (); } void display_cb() { glClear(GL_COLOR_BUFFER_BIT); //------------------------------------------------------------------------------ ///LO UNICO QUE ME QUEDA SOLUCIONAR SON ERRORES DE PRECISION... LOS BIAS DE ERROR ME HACEN CAGADA... if(!hecho){ for(int i=0;i<50;i++){ S.push_back(Get_Segment()); } for(int i = 0; i< S.size();i++){ glColor3f(.0f,.0f,.0f); glLineWidth(1.0f); glBegin(GL_LINES); glVertex2d(S[i].ini.x,S[i].ini.y); glVertex2d(S[i].fin.x,S[i].fin.y); glEnd(); glColor3f(1.0f,.0f,.0f); glPointSize(3.0f); glBegin(GL_POINTS); glVertex2d(S[i].ini.x,S[i].ini.y); glVertex2d(S[i].fin.x,S[i].fin.y); glEnd(); } ///-------------------------------------------------------------------- Interseccion i; ///ERROR, NO ME ESTA HACIENDO BIEN EL SWAP DE LOS SEGMENTOS... ///REALIZAR UN SEGUIMIENTO DEL ALGORITMO PARA VERIFICAR LOS CASOS... ///MUY PROBABLE PROBLEMA DE PRECISION... i.FindIntersection(S); I = i.GetIntersection(); if(!I.empty()){ cout<<"HAY INTERSECCION: "<< I.size()<<endl; } hecho = true; } //------------------------------------------------------------------------------ else{ for(int i = 0; i< S.size();i++){ glColor3f(.0f,.0f,.0f); glLineWidth(1.0f); glBegin(GL_LINES); glVertex2d(S[i].ini.x,S[i].ini.y); glVertex2d(S[i].fin.x,S[i].fin.y); glEnd(); glColor3f(1.0f,.0f,.0f); glPointSize(3); glBegin(GL_POINTS); glVertex2d(S[i].ini.x,S[i].ini.y); glVertex2d(S[i].fin.x,S[i].fin.y); glEnd(); } if(!I.empty()){ for(int i = 0; i< I.size();i++){ glColor3f(.0f,.0f,1.0f); glPointSize(3); glBegin(GL_POINTS); glVertex2d(I[i].x,I[i].y); glEnd(); } } } glutSwapBuffers(); } void initialize() { glutInitDisplayMode (GLUT_RGBA|GLUT_DOUBLE); glutInitWindowSize (640,480); glutInitWindowPosition (100,100); glutCreateWindow ("Ventana OpenGL"); glutDisplayFunc (display_cb); glutReshapeFunc (reshape_cb); glClearColor(1.f,1.f,1.f,1.f); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ /////INSERT Y DELETE FUNCIONAN MEJOR... // //Arbol_B<int> A; //A.Insert(1); //A.Insert(2); //A.Insert(3); //A.Insert(4); //A.Insert(5); //A.Insert(6); //A.Insert(7); // //A.Delete(1); //A.Delete(2); //A.Delete(3); //A.Delete(4); //A.Delete(5); //A.Delete(6); //A.Delete(7); // //A.show(); // //------------------------------------------------------------------------------ // int *a; // int *b; // int c = 1; // b = &c; // a = b; // cout<<*a<<endl; // // b = 0; // // cout<<*a<<endl; } int main (int argc, char **argv) { srand(time(NULL)); glutInit (&argc, argv); initialize(); glutMainLoop(); return 0; }
f63ed3b7c6203f14c151b689ab187250185dda7f
[ "C++" ]
6
C++
MaineroFrancisco/Geometria-Computacional
c13b6e4a23e31ce50dadd8239a931e8fd2ec01fe
822464d0f90b0d6fcee1622c97b156cb4f1d195d
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OwnProject.Views { public class Display { public double Budget { get; set; } public string Season { get; set; } public string Country { get; set; } public string Accomodation { get; set; } public double Price { get; set; } public Display() { getvalues(); } public void getvalues() { Budget = double.Parse(Console.ReadLine()); Season = Console.ReadLine(); } public void Print() { Console.WriteLine(Country); Console.WriteLine(Accomodation + " - " + Price); } } } <file_sep>using OwnProject.Models; using OwnProject.Views; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OwnProject.Controllers { public class Controller { private Display display; private VacationModel vacation; public Controller() { display = new Display(); vacation = new VacationModel(display.Budget, display.Season); } public void StartUp() { display.Country = vacation.Country; display.Accomodation = vacation.Accomodation; display.Price = vacation.CalculatePrice(); display.Print(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OwnProject.Models { public class VacationModel { public double Budget { get; set; } public string Season { get; set; } public string Country { get; set; } public string Accomodation { get; set; } public double Price { get; set; } = 0; public VacationModel(double budget, string season) { this.Budget = budget; this.Season = season; } public double CalculatePrice() { if(Budget <= 100) { if(Season == "summer") { this.Price = Budget * (30 / 100); Accomodation = "Camp"; Country = "Somewhere in Bulgaria"; } else { Accomodation = "Hotel"; Country = "Somewhere in Bulgaria"; Price = Budget * (70 / 100); } } if (Budget <= 1000 && Budget > 100) { if (Season == "summer") { Accomodation = "Camp"; Country = "Somewhere in Balkans"; Price = Budget * (40 / 100); } else { Accomodation = "Hotel"; Country = "Somewhere in Balkans"; Price = Budget * (80 / 100); } } if (Budget > 1000) { Accomodation = "Hotel"; Country = "Somewhere in Europe"; Price = Budget * (90 / 100); } return Price; } } }
a823fbd4807a1152148b1a4aacb3b41a4ab43f3c
[ "C#" ]
3
C#
KonakovBG/C-Project
ab29a8782383340bcc70d4eb9d694e163527d009
21a6687962303add9834861957058bb7df353147
refs/heads/master
<repo_name>SWS-Methodology/faoswsStandardization<file_sep>/modules/SUA_bal_compilation_round2021/main.R library(faosws) library(faoswsUtil) library(faoswsBalancing) library(faoswsProcessing) library(faoswsStandardization) library(dplyr) library(data.table) library(tidyr) library(openxlsx) # The only parameter is the string to print # COUNTRY is taken from environment (parameter) dbg_print <- function(x) { message(paste0("NEWBAL (", COUNTRY, "): ", x)) } start_time <- Sys.time() R_SWS_SHARE_PATH <- Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { R_SWS_SHARE_PATH <- "//hqlprsws1.hq.un.fao.org/sws_r_share" mydir <- "modules/SUA_bal_compilation_round2021" SETTINGS <- faoswsModules::ReadSettings(file.path(mydir, "sws.yml")) SetClientFiles(SETTINGS[["certdir"]]) GetTestEnvironment(baseUrl = SETTINGS[["server"]], token = SETTINGS[["token"]]) } startYear = as.numeric(swsContext.computationParams$startYear) endYear = as.numeric(swsContext.computationParams$endYear) stopifnot(startYear <= endYear) yearVals = startYear:endYear COUNTRY <- as.character(swsContext.datasets[[1]]@dimensions$geographicAreaM49@keys) COUNTRY_suaunbal <- as.character(swsContext.datasets[[2]]@dimensions$geographicAreaM49@keys) COUNTRY_shareup <- as.character(swsContext.datasets[[3]]@dimensions$geographicAreaM49@keys) COUNTRY_sharedown <- as.character(swsContext.datasets[[4]]@dimensions$geographicAreaM49@keys) if(sum(COUNTRY == c(COUNTRY_suaunbal,COUNTRY_sharedown,COUNTRY_shareup)) < 3){ dbg_print("Session countries are not identical") print(paste0("Session countries are not identical")) stop("Session countries are not identical") } COUNTRY_NAME <- nameData( "suafbs", "sua_unbalanced", data.table(geographicAreaM49 = COUNTRY))$geographicAreaM49_description dbg_print("parameters") USER <- regmatches( swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE) ) # if (!file.exists(file.path(R_SWS_SHARE_PATH, USER))) { # dir.create(file.path(R_SWS_SHARE_PATH, USER)) # } STOP_AFTER_DERIVED <- as.logical(swsContext.computationParams$stop_after_derived) THRESHOLD_METHOD <- 'share' FIX_OUTLIERS <- TRUE FILL_EXTRACTION_RATES <- TRUE YEARS <- as.character(2000:endYear) TMP_DIR <- file.path(tempdir(), USER) if (!file.exists(TMP_DIR)) dir.create(TMP_DIR, recursive = TRUE) tmp_file_imb <- file.path(TMP_DIR, paste0("IMBALANCE_", COUNTRY, ".xlsx")) tmp_file_shares <- file.path(TMP_DIR, paste0("SHARES_", COUNTRY, ".xlsx")) tmp_file_losses_to_check <- file.path(TMP_DIR, paste0("LOSSES_TO_CHECK_", COUNTRY, ".xlsx")) tmp_file_industrial_to_check <- file.path(TMP_DIR, paste0("INDUSTRIAL_TO_CHECK_", COUNTRY, ".xlsx")) #tmp_file_negative <- file.path(TMP_DIR, paste0("NEGATIVE_AVAILAB_", COUNTRY, ".csv")) #tmp_file_non_exist <- file.path(TMP_DIR, paste0("NONEXISTENT_", COUNTRY, ".csv")) #tmp_file_fix_shares <- file.path(TMP_DIR, paste0("FIXED_PROC_SHARES_", COUNTRY, ".csv")) #tmp_file_NegNetTrade <- file.path(TMP_DIR, paste0("NEG_NET_TRADE_", COUNTRY, ".csv")) tmp_file_Stock_correction <- file.path(TMP_DIR, paste0("STOCK_CORRECTION_", COUNTRY, ".csv")) # Always source files in R/ (useful for local runs). # Your WD should be in faoswsStandardization/ sapply(dir("R", full.names = TRUE), source) p <- defaultStandardizationParameters() p$itemVar <- "measuredItemSuaFbs" p$mergeKey[p$mergeKey == "measuredItemCPC"] <- "measuredItemSuaFbs" p$elementVar <- "measuredElementSuaFbs" p$childVar <- "measuredItemChildCPC" p$parentVar <- "measuredItemParentCPC" p$createIntermetiateFile <- "TRUE" p$protected <- "Protected" p$official <- "Official" shareDownUp_file <- file.path(R_SWS_SHARE_PATH, USER, paste0("shareDownUp_", COUNTRY, ".csv")) tourist_cons_table <- ReadDatatable("keep_tourist_consumption") stopifnot(nrow(tourist_cons_table) > 0) TourismNoIndustrial <- tourist_cons_table[small == "X"]$tourist NonSmallIslands<-tourist_cons_table[small != "X"]$tourist dbg_print("define functions") ######### FUNCTIONS: at some point, they will be moved out of this file. #### # Replacement for merge(x, y, by = VARS, all.x = TRUE) that do not set keys # By default it behaves as dplyr::left_join(). If nomatch = 0, non-matching # rows will not be returned dt_left_join <- function(x, y, by = NA, allow.cartesian = FALSE, nomatch = NA) { if (anyNA(by)) { stop("'by' is required") } if (any(!is.data.table(x), !is.data.table(y))) { stop("'x' and 'y' should be data.tables") } res <- y[x, on = by, allow.cartesian = allow.cartesian, nomatch = nomatch] setcolorder(res, c(names(x), setdiff(names(y), names(x)))) res } dt_full_join <- function(x, y, by = NA) { if (anyNA(by)) { stop("'by' is required") } if (any(!is.data.table(x), !is.data.table(y))) { stop("'x' and 'y' should be data.tables") } res <- merge(x, y, by = by, all = TRUE) # merge sets the key to `by` setkey(res, NULL) res } message("Line 140") #function used for countries which had stock data in the past (before 2014) #linearization taking into account the supply before 2013. coeffs_stocks_mod <- function(x) { tmp <- lm(data = x[timePointYears < startYear], supply_inc ~ supply_exc + trend) as.list(tmp$coefficients) } # This function will recalculate opening stocks from the first # observation. Always. update_opening_stocks <- function(x) { x <- x[order(geographicAreaM49, measuredItemSuaFbs, timePointYears)] groups <- unique(x[, c("geographicAreaM49", "measuredItemSuaFbs"), with = FALSE]) res <- list() for (i in seq_len(nrow(groups))) { z <- x[groups[i], on = c("geographicAreaM49", "measuredItemSuaFbs")] if (nrow(z) > 1) { for (j in seq_len(nrow(z))[-1]) { # negative delta cannot be more than opening if (z$delta[j-1] < 0 & abs(z$delta[j-1]) > z$new_opening[j-1]) { z$delta[j-1] <- - z$new_opening[j-1] } z$new_opening[j] <- z$new_opening[j-1] + z$delta[j-1] } # negative delta cannot be more than opening if (z$delta[j] < 0 & abs(z$delta[j]) > z$new_opening[j]) { z$delta[j] <- - z$new_opening[j] } } res[[i]] <- z } rbindlist(res) } # Fill NAs by LOCF/FOCB/interpolation if more than two # non-missing observations are available, otherwhise just # replicate the only non-missing observation na.fill_ <- function(x) { if(sum(!is.na(x)) > 1) { zoo::na.fill(x, "extend") } else { rep(x[!is.na(x)], length(x)) } } `%!in%` <- Negate(`%in%`) # RemainingToProcessedParent() and RemainingProdChildToAssign() will # be used in the derivation of shareDownUp RemainingToProcessedParent <- function(data) { data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] data[, only_child_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(production_of_child) & !is.na(parent_qty_processed) & production_of_child > 0, by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[ only_child_left == TRUE, processed_to_child := remaining_processed_parent * extractionRate ] data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] return(data) } RemainingProdChildToAssign <- function(data) { data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] data[, only_parent_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(parent_qty_processed) & parent_qty_processed >= 0 ] data[only_parent_left==TRUE,processed_to_child:=ifelse(only_parent_left==TRUE,remaining_to_process_child,processed_to_child)] data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] return(data) } # The fmax function is used when fixing the processingShare of coproducts. # If TRUE it means that "+" or "or" cases are involved. fmax <- function(child, main, share, plusor = FALSE) { main <- unique(main) if (plusor) { found <- sum(sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)) if (found == 0) { return(max(share, na.rm = TRUE)) } else if (found == 1) { return( share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]] ) } else { # should be 2 return(max(share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]], na.rm = TRUE)) } } else { if (sum(grepl(main, child)) > 0) { share[child == main] } else { max(share, na.rm = TRUE) } } } # Function that calculates imbalance as supply - utilizations (both calculated # inside the function, dropped if keep_(supply|utilizations) set to FALSE). calculateImbalance <- function(data, supply_add = c("production", "imports"), supply_subtract = c("exports", "stockChange"), supply_all = union(supply_add, supply_subtract), item_name = "measuredItemSuaFbs", bygroup = c("geographicAreaM49", "timePointYears", item_name), keep_supply = TRUE, keep_utilizations = TRUE) { stopifnot(is.data.table(data)) data[, `:=`( supply = sum(Value[measuredElementSuaFbs %chin% supply_add], - Value[measuredElementSuaFbs %chin% supply_subtract], na.rm = TRUE), # All elements that are NOT supply elements utilizations = sum(Value[!(measuredElementSuaFbs %chin% supply_all)], na.rm = TRUE) ), by = bygroup ][, imbalance := supply - utilizations ] if (keep_supply == FALSE) { data[, supply := NULL] } if (keep_utilizations == FALSE) { data[, utilizations := NULL] } } outside <- function(x, lower = NA, upper = NA) { x < lower | x > upper } send_mail <- function(from = NA, to = NA, subject = NA, body = NA, remove = FALSE) { if (missing(from)) from <- '<EMAIL>' if (missing(to)) { if (exists('swsContext.userEmail')) { to <- swsContext.userEmail } } if (is.null(to)) { stop('No valid email in `to` parameter.') } if (missing(subject)) stop('Missing `subject`.') if (missing(body)) stop('Missing `body`.') if (length(body) > 1) { body <- sapply( body, function(x) { if (file.exists(x)) { # https://en.wikipedia.org/wiki/Media_type file_type <- switch( tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), txt = 'text/plain', csv = 'text/csv', png = 'image/png', jpeg = 'image/jpeg', jpg = 'image/jpeg', gif = 'image/gif', xls = 'application/vnd.ms-excel', xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', doc = 'application/msword', docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf = 'application/pdf', zip = 'application/zip', # https://stackoverflow.com/questions/24725593/mime-type-for-serialized-r-objects rds = 'application/octet-stream' ) if (is.null(file_type)) { stop(paste(tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), 'is not a supported file type.')) } else { res <- sendmailR:::.file_attachment(x, basename(x), type = file_type) if (remove == TRUE) { unlink(x) } return(res) } } else { return(x) } } ) } else if (!is.character(body)) { stop('`body` should be either a string or a list.') } sendmailR::sendmail(from, to, subject, as.list(body)) } balance_proportional <- function(data) { x <- copy(data) x <- x[ can_balance == TRUE, c("measuredElementSuaFbs", "Value", "mov_share", "imbalance", "min_threshold", "max_threshold", "can_balance"), with = FALSE ] mov_share_sum <- sum(x$mov_share, na.rm = TRUE) if (mov_share_sum > 0) { # Recalculate mov_share, as we are excluding protected values x[, mov_share := mov_share / mov_share_sum] } else { # It means that there are no back shares, so use current values x[!is.na(Value) & can_balance == TRUE, mov_share := Value / sum(Value, na.rm = TRUE)] } x[is.na(Value), Value := 0] x[, adjusted_value := 0] x[Value + mov_share * imbalance >= 0, adjusted_value := Value + mov_share * imbalance] x[adjusted_value > Value & adjusted_value > max_threshold, adjusted_value := max_threshold] x[adjusted_value < Value & adjusted_value < min_threshold, adjusted_value := min_threshold] x <- x[, c("measuredElementSuaFbs", "adjusted_value"), with = FALSE][data, on = "measuredElementSuaFbs"] return(as.numeric(x$adjusted_value)) } # rollavg() is a rolling average function that uses computed averages # to generate new values if there are missing values (and FOCB/LOCF). # I.e.: # vec <- c(NA, 2, 3, 2.5, 4, 3, NA, NA, NA) # #> RcppRoll::roll_mean(myvec, 3, fill = 'extend', align = 'right') #[1] NA NA NA 2.500000 3.166667 3.166667 NA NA NA # #> rollavg(myvec) #[1] 2.000000 2.000000 3.000000 2.500000 4.000000 3.000000 3.166667 3.388889 3.185185 rollavg <- function(x, order = 3) { # order should be > 2 stopifnot(order >= 3) non_missing <- sum(!is.na(x)) # For cases that have just two non-missing observations order <- ifelse(order > 2 & non_missing == 2, 2, order) if (non_missing == 1) { x[is.na(x)] <- na.omit(x)[1] } else if (non_missing >= order) { n <- 1 while(any(is.na(x)) & n <= 10) { # 10 is max tries movav <- suppressWarnings(RcppRoll::roll_mean(x, order, fill = 'extend', align = 'right')) movav <- data.table::shift(movav) x[is.na(x)] <- movav[is.na(x)] n <- n + 1 } x <- zoo::na.fill(x, 'extend') } return(x) } newBalancing <- function(data, Utilization_Table) { # Contains a variable that indicates whether stocks changed data[, change_stocks := NA_integer_] # XXX define "food residual" those items for which the only utilization # is food. Food processing can also be another possible utilization and # if there is that does not change its food-residualness, this is why # the check is done before assigning food processing. # NW: I have commented the conditions out # Now it only checks to make sure that food is the only utilization # We noticed that some of the food items were missing from the utilization table # This is still different from the previous approach of assigning all of the imbalance to # food when "none of the other utilizations are activable" data[, food_resid := # It's a food item & ... (measuredItemSuaFbs %chin% Utilization_Table[food_item == 'X', cpc_code] | # food exists & ... # !is.na(Value[measuredElementSuaFbs == 'food']) & Food_Median > 0 & !is.na(Food_Median)) & # ... is the only utilization all(is.na(Value[!(measuredElementSuaFbs %chin% c('loss', 'food', 'production', 'imports', 'exports', 'stockChange','foodManufacturing', 'tourist'))])), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # 0143 Cottonseed # 01442 Mustard seed # 01443 Rapeseed or colza seed # 01446 Safflower seed # 01449.90 Other oil seeds, n.e. # 01491.02 Palm kernels # 01801 Sugar beet # 01802 Sugar cane # 01809 Other sugar crops n.e. special_list<-c("0143","01442","01443","01446","01449.90","01491.02","01801","01802","01809") data[measuredItemSuaFbs %chin% special_list, food_resid := # It's a food item & ... (measuredItemSuaFbs %chin% Utilization_Table[food_item == 'X', cpc_code] & # food exists & ... # !is.na(Value[measuredElementSuaFbs == 'food']) & Food_Median > 0 & !is.na(Food_Median)) & # ... is the only utilization all(is.na(Value[!(measuredElementSuaFbs %chin% c('loss', 'food', 'production', 'imports', 'exports', 'stockChange','foodManufacturing', 'tourist'))])), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # Checking if the commodity has past value before assigning the residual # imbalance at the end of the balancing procees data[, `:=`( feed_resid = # It's a feed item or have past value & ... #(measuredItemSuaFbs %in% Utilization_Table[feed == 'X', cpc_code] | (Feed_Median > 0 & !is.na(Feed_Median)) & #feed is the only utilization.... all(is.na(Value[!(measuredElementSuaFbs %chin% c('feed', 'production', 'imports', 'exports', 'stockChange','foodManufacturing'))])), # It's a industrial item or have past value & ... industrial_resid = Industrial_Median > 0 & !is.na(Industrial_Median)), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] data[, supply := sum( Value[measuredElementSuaFbs %chin% c('production', 'imports')], - Value[measuredElementSuaFbs %chin% c('exports')], na.rm = TRUE ), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # #BLOCKING not Industrial items from FBS cycle 2021 all countries - livia not_industrial_table <- ReadDatatable("not_industrial_use_table") not_industrial <- not_industrial_table[not_industrial %in% "X",]$cpc_code data[measuredItemSuaFbs %in% not_industrial & measuredElementSuaFbs %in% "industrial" & Value > 0 & !is.na(Value), `:=`(industrial_resid = FALSE , Value = 0 , flagObservationStatus = "E" , flagMethod = "f" , Protected = TRUE)] calculateImbalance(data) # When production needs to be created # data[ # Protected == FALSE & # # Only primary # measuredItemSuaFbs %chin% Utilization_Table[primary_item == "X"]$cpc_code & # measuredElementSuaFbs == 'production' & # supply < 0 & # stockable == FALSE & # !is.na(Value) & Value != 0, # `:=`( # Value = Value - imbalance, # flagObservationStatus = "E", # flagMethod = "c" # )] # calculateImbalance(data) # if we have new production or new imports, we assign the imbalance to food (if it is a food item) or to feed(it is a feed item) data[imbalance>0 & (is.na(Production_Median)|Production_Median==0)& (is.na(Import_Median)|Import_Median==0) & Protected==FALSE & measuredElementSuaFbs== "food" & measuredItemSuaFbs %chin% Utilization_Table[food_item == "X"]$cpc_code, `:=`( Value = ifelse( is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, 0) ), flagObservationStatus = "E", flagMethod = "h" ) ] # recalculate imbalance calculateImbalance(data) data[imbalance>0 & (is.na(Production_Median)|Production_Median==0)&(is.na(Import_Median)|Import_Median==0) & Protected==FALSE & measuredElementSuaFbs== "feed" & measuredItemSuaFbs %chin% Utilization_Table[feed == "X"]$cpc_code, `:=`( Value = ifelse( is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, 0) ), flagObservationStatus = "E", flagMethod = "h" ) ] # recalculate imbalance calculateImbalance(data) # Try to assign the maximum of imbalance to stocks # NOTE: in the conditions below, 2 was 0.2, indicating that no more than # 20% should go to stocks. Now, the condition was relaxed a lot (200%) data <- dt_left_join( data, all_opening_stocks[, .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, opening_stocks = Value) ], by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data[, Value_0 := ifelse(is.na(Value), 0, Value) ][ Protected == FALSE & dplyr::near(imbalance, 0) == FALSE & measuredElementSuaFbs == "stockChange" & stockable == TRUE, change_stocks := # The numbers indicate the case. Assignmnet (value and flags) will be done below case_when( # case 1: we don't want stocks to change sign. sign(Value_0) * sign(Value_0 + imbalance) == -1 ~ 1L, # case 2: if value + imbalance takes LESS than opening stock, take all from stocks Value_0 <= 0 & (Value_0 + imbalance <= 0) & abs(Value_0 + imbalance) <= opening_stocks ~ 2L, # case 3: if value + imbalance takes MORE than opening stock, take max opening stocks Value_0 <= 0 & (Value_0 + imbalance <= 0) & abs(Value_0 + imbalance) > opening_stocks ~ 3L, # case 4: if value + imbalance send LESS than 200% of supply, send all Value_0 >= 0 & (Value_0 + imbalance >= 0) & (Value_0 + imbalance + opening_stocks <= supply * 2) ~ 4L, # case 5: if value + imbalance send MORE than 200% of supply, send 200% of supply Value_0 >= 0 & (Value_0 + imbalance >= 0) & (Value_0 + imbalance + opening_stocks > supply * 2) ~ 5L ) ] data[change_stocks == 1L, Value := 0] data[change_stocks == 2L, Value := Value_0 + imbalance] data[change_stocks == 3L, Value := - opening_stocks] data[change_stocks == 4L, Value := Value_0 + imbalance] # Only case for which grouping is required data[ change_stocks == 5L, Value := max(supply * 2 - opening_stocks, 0), by = c("geographicAreaM49", "measuredItemSuaFbs") ] data[ change_stocks %in% 1L:5L, `:=`(flagObservationStatus = "E", flagMethod = "s") ] data[, Value_0 := NULL] data[, opening_stocks := NULL] # Recalculate imbalance calculateImbalance(data) # Assign imbalance to food if food "only" (not "residual") item data[ Protected == FALSE & food_resid == TRUE & dplyr::near(imbalance, 0) == FALSE & measuredElementSuaFbs == "food", `:=`( Value = ifelse(is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, 0)), flagObservationStatus = "E", flagMethod = "h" ) ] if (COUNTRY %in% TourismNoIndustrial) { data[measuredElementSuaFbs == "tourist" & flagMethod != "f", Protected := FALSE] adj_tour_ind <- data.table::dcast( data[ measuredItemSuaFbs %chin% Utilization_Table[food_item == "X"]$cpc_code & measuredElementSuaFbs %chin% c("industrial", "tourist") ], geographicAreaM49 + timePointYears + measuredItemSuaFbs ~ measuredElementSuaFbs, value.var = "Value" ) adj_tour_ind <- adj_tour_ind[industrial > 0] adj_tour_ind[, new_tourist := industrial] adj_tour_ind[!is.na(tourist), new_tourist :=industrial] adj_tour_ind[, c("industrial", "tourist") := NULL] by_vars <- c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") data <- dt_left_join(data, adj_tour_ind, by = by_vars) data[ measuredElementSuaFbs %in% c("industrial", "tourist"), any_protected := any(Protected == TRUE), by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ] data[ !is.na(new_tourist) & measuredElementSuaFbs == "tourist" & any_protected == FALSE, `:=`( Value = new_tourist, flagObservationStatus = "E", flagMethod = "e" ) ] data[ !is.na(new_tourist) & measuredElementSuaFbs == "industrial" & any_protected == FALSE, `:=`( Value = 0, flagObservationStatus = "E", flagMethod = "e" ) ] data[, c("any_protected", "new_tourist") := NULL] data[measuredElementSuaFbs == "tourist", Protected := TRUE] } for (j in 1:10) { # Recalculate imbalance calculateImbalance(data) data[, can_balance := FALSE] data[ !is.na(Value) & Protected == FALSE & !(data.table::between(Value, min_threshold, max_threshold, incbounds = FALSE) %in% FALSE) & !(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange", "foodManufacturing", "seed")), can_balance := TRUE ] data[, elements_balance := any(can_balance), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] if (nrow(data[dplyr::near(imbalance, 0) == FALSE & elements_balance == TRUE]) == 0) { break() } else { data[ dplyr::near(imbalance, 0) == FALSE & elements_balance == TRUE, adjusted_value := balance_proportional(.SD), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] data[ !is.na(adjusted_value) & !dplyr::near(adjusted_value, Value), `:=`( Value = adjusted_value, flagObservationStatus = "E", flagMethod = "-" ) ] data[, adjusted_value := NULL] } } # At this point the imbalance (in the best case scenario) should be zero, # the following re-calculation is useful only for debugging calculateImbalance(data) # Assign imbalance to food if food "only" (not "residual") item data[ Protected == FALSE & food_resid == TRUE & dplyr::near(imbalance, 0) == FALSE & measuredElementSuaFbs == "food", `:=`( Value = ifelse( is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, 0) ), flagObservationStatus = "E", flagMethod = "h" ) ] calculateImbalance(data) # Assign the residual imbalance to industrial if the conditions are met data[geographicAreaM49 %in% TourismNoIndustrial & measuredItemSuaFbs %in% Utilization_Table[food_item == 'X', cpc_code], industrial_resid := FALSE ] data[ Protected == FALSE & industrial_resid == TRUE & dplyr::near(imbalance, 0) == FALSE & measuredElementSuaFbs == "industrial", `:=`( Value = ifelse( is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, Value) ), flagObservationStatus = "E", flagMethod = "b" ) ] calculateImbalance(data) # Assign the residual imbalance to feed if the conditions are met data[ Protected == FALSE & feed_resid == TRUE & dplyr::near(imbalance, 0) == FALSE & measuredElementSuaFbs == "feed", `:=`( # XXX: this creates a warning when no assignment is done: # Coerced 'logical' RHS to 'double' Value = ifelse( is.na(Value) & imbalance > 0, imbalance, ifelse(Value + imbalance >= 0, Value + imbalance, Value) ), flagObservationStatus = "E", flagMethod = "b" ) ] calculateImbalance(data) data[, c("supply", "utilizations", "imbalance", "mov_share_rebased") := NULL] return(data) } ############################## / FUNCTIONS ################################## dbg_print("end functions") ##################################### TREE ################################# message("Line 816") dbg_print("download tree") tree <- getCommodityTreeNewMethod(COUNTRY, YEARS) stopifnot(nrow(tree) > 0) tree <- tree[geographicAreaM49 %chin% COUNTRY] # The `tree_exceptions` will npo be checked by validateTree() # Exception: high share conmfirmed by official data tree_exceptions <- tree[geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01"] if (nrow(tree_exceptions) > 0) { tree <- tree[!(geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01")] } validateTree(tree) if (nrow(tree_exceptions) > 0) { tree <- rbind(tree, tree_exceptions) rm(tree_exceptions) } ## NA ExtractionRates are recorded in the sws dataset as 0 ## for the standardization, we nee them to be treated as NA ## therefore here we are re-changing it # TODO: Keep all protected 0 ERs tree[Value == 0 & !(flagObservationStatus == "E" & flagMethod == "f"), Value := NA] #proc_level_exceptions <- ReadDatatable("processing_level_exceptions") # #if (nrow(proc_level_exceptions) > 0) { # setnames(proc_level_exceptions, c("m49_code", "parent", "child"), # c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC")) # # tree <- # tree[!proc_level_exceptions[is.na(level)], # on = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC")] # # proc_level_exceptions <- proc_level_exceptions[!is.na(level)] #} tree_to_send <- tree[is.na(Value) & measuredElementSuaFbs=="extractionRate"] message("Line 864") if (FILL_EXTRACTION_RATES == TRUE) { expanded_tree <- merge( data.table( geographicAreaM49 = unique(tree$geographicAreaM49), timePointYears = as.character(sort(2000:endYear)) ), unique( tree[, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC"), with = FALSE ] ), by = "geographicAreaM49", all = TRUE, allow.cartesian = TRUE ) tree <- tree[expanded_tree, on = colnames(expanded_tree)] # flags for carry forward/backward tree[is.na(Value), c("flagObservationStatus", "flagMethod") := list("E", "t")] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = -Inf ] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = Inf ] # keep orig flags tree[, flagObservationStatus := i.i.flagObservationStatus] tree[, flagMethod := i.i.flagMethod] tree[, names(tree)[grep("^i\\.", names(tree))] := NULL] } # XXX: connections removed here that should not exist in # the commodity tree (so, they should be fixed there) tree[ #timePointYears >= 2014 & ((measuredItemParentCPC == "02211" & measuredItemChildCPC == "22212") | #cheese from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22251.01") | (measuredItemParentCPC == "02211" & measuredItemChildCPC == "22251.02") ), `:=`( Value = NA, flagObservationStatus = "M", flagMethod = "n" ) ] #correction of milk tree for Czechia TO DO: generalize for the next round tree[ timePointYears >= startYear & geographicAreaM49=="203" & #“whole milk powder” from whole cow milk cannot come from skim mulk of cow ((measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22211") | #“whole milk condensed” from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22222.01")), `:=`( Value = NA, flagObservationStatus = "M", flagMethod = "n" ) ] # saveRDS( # tree[ # !is.na(Value) & measuredElementSuaFbs == "extractionRate", # -grepl("measuredElementSuaFbs", names(tree)), # with = FALSE # ], # file.path(R_SWS_SHARE_PATH, "FBSvalidation", COUNTRY, "tree.rds") # ) tree_to_send <- tree_to_send %>% dplyr::anti_join( tree[is.na(Value) & measuredElementSuaFbs == "extractionRate"], by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod") ) %>% dplyr::select(-Value) %>% dplyr::left_join( tree, by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "flagObservationStatus", "flagMethod") ) %>% setDT() tree_to_send <- tree_to_send[, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] setnames( tree_to_send, c("measuredItemParentCPC", "measuredItemChildCPC"), c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree") ) tree_to_send <- nameData("suafbs", "ess_fbs_commodity_tree2", tree_to_send, except = c('measuredElementSuaFbs', 'timePointYears')) tree_to_send[, `:=`( measuredItemParentCPC_tree = paste0("'", measuredItemParentCPC_tree), measuredItemChildCPC_tree = paste0("'", measuredItemChildCPC_tree)) ] # tmp_file_extr <- file.path(TMP_DIR, paste0("FILLED_ER_", COUNTRY, ".csv")) # # write.csv(tree_to_send, tmp_file_extr) # XXX remove NAs tree <- tree[!is.na(Value)] uniqueLevels <- unique(tree[, c("geographicAreaM49", "timePointYears"), with = FALSE]) levels <- list() treeLevels <- list() for (i in seq_len(nrow(uniqueLevels))) { filter <- uniqueLevels[i, ] treeCurrent <- tree[filter, on = c("geographicAreaM49", "timePointYears")] levels <- findProcessingLevel(treeCurrent, "measuredItemParentCPC", "measuredItemChildCPC") setnames(levels, "temp", "measuredItemParentCPC") treeLevels[[i]] <- dt_left_join(treeCurrent, levels, by = "measuredItemParentCPC") } tree <- rbindlist(treeLevels) tree[, processingLevel := max(processingLevel, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredElementSuaFbs", "measuredItemChildCPC") ] # XXX Check if this one is still good or it can be obtained within the dataset processed_item_datatable <- ReadDatatable("processed_item") processedCPC <- processed_item_datatable[, measured_item_cpc] # XXX Get codes to exclude animals from imbalances file at the end itemMap <- GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemMap <- itemMap[, .(measuredItemSuaFbs = code, type)] ##################################### / TREE ################################ ############################ POPULATION ##################################### key <- DatasetKey( domain = "population", dataset = "population_unpd", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = "511"), # 511 = Total population timePointYears = Dimension(name = "timePointYears", keys = as.character(2000:endYear)) ) ) dbg_print("download population") popSWS <- GetData(key) stopifnot(nrow(popSWS) > 0) popSWS[geographicAreaM49 == "156", geographicAreaM49 := "1248"] # Fix for missing regional official data in the country total # Source: DEMOGRAPHIC SURVEY, Kurdistan Region of Iraq, July 2018, IOM UN Migration # ("the KRI population at 5,122,747 individuals and the overall Iraqi # population at 36,004,552 individuals", pag.14; it implies 14.22805%) # https://iraq.unfpa.org/sites/default/files/pub-pdf/KRSO%20IOM%20UNFPA%20Demographic%20Survey%20Kurdistan%20Region%20of%20Iraq_0.pdf popSWS[geographicAreaM49 == "368" & timePointYears %in% startYear:endYear, Value := Value * 0.8577195] ############################ / POPULATION ################################## ############################################################### DATA ####### # 5510 Production[t] # 5610 Import Quantity [t] # 5071 Stock Variation [t] # 5023 Export Quantity [t] # 5910 Loss [t] # 5016 Industrial uses [t] # 5165 Feed [t] # 5520 Seed [t] # 5525 Tourist Consumption [t] # 5164 Residual other uses [t] # 5141 Food [t] # 664 Food Supply (/capita/day) [Kcal] elemKeys <- c("5510", "5610", "5071", "5113", "5023", "5910", "5016", "5165", "5520", "5525", "5164", "5166", "5141") itemKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys <- itemKeys$code # NOTE: the definition of "food_resid" changed (see inside newBalancing) # (so, the tables below are not used anymore) #food_classification_country_specific <- # ReadDatatable("food_classification_country_specific", # where = paste0("geographic_area_m49 IN ('", COUNTRY, "')")) # #food_classification_country_specific <- # food_classification_country_specific[geographic_area_m49 == COUNTRY] # #food_only_items <- food_classification_country_specific[food_classification == 'Food Residual', measured_item_cpc] Utilization_Table <- ReadDatatable("utilization_table_2018") stockable_items <- Utilization_Table[stock == 'X', cpc_code] zeroWeight <- ReadDatatable("zero_weight")[, item_code] flagValidTable <- ReadDatatable("valid_flags") # We decided to unprotect E,e (replaced outliers). Done after they are # replaced (i.e., if initially an Ee exists, it should remain; they need # to be unprotected for balancing. flagValidTable[flagObservationStatus == 'E' & flagMethod == 'e', Protected := FALSE] # XXX: we need to unprotect I,c because it was being assigned # to imputation of production of derived which is NOT protected. # This will need to change in the next exercise. flagValidTable[flagObservationStatus == 'I' & flagMethod == 'c', Protected := FALSE] # Nutrients are: # 1001 Calories # 1003 Proteins # 1005 Fats nutrientCodes = c("1001", "1003", "1005") nutrientData <- getNutritiveFactors( measuredElement = nutrientCodes, timePointYears = as.character(startYear:endYear), geographicAreaM49 = COUNTRY ) ######### CREAM SWEDEN nutrientData[geographicAreaM49=="752" & measuredItemCPC=="22120"& measuredElement=="1001",Value:=195] nutrientData[geographicAreaM49=="752" & measuredItemCPC=="22120"& measuredElement=="1003",Value:=3] nutrientData[geographicAreaM49=="752" & measuredItemCPC=="22120"& measuredElement=="1005",Value:=19] ### MILK SWEDEN nutrientData[geographicAreaM49%in%c("756","300","250","372","276")& measuredItemCPC=="22251.01"& measuredElement=="1001",Value:=387] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")& measuredItemCPC=="22251.01"& measuredElement=="1003",Value:=26] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")& measuredItemCPC=="22251.01"& measuredElement=="1005",Value:=30] nutrientData[geographicAreaM49=="300"& measuredItemCPC=="22253"& measuredElement=="1001",Value:=310] nutrientData[geographicAreaM49=="300"& measuredItemCPC=="22253"& measuredElement=="1003",Value:=23] nutrientData[geographicAreaM49=="300"& measuredItemCPC=="22253"& measuredElement=="1005",Value:=23] nutrientData[measuredElement=="1001",measuredElement:="664"] nutrientData[measuredElement=="1003",measuredElement:="674"] nutrientData[measuredElement=="1005",measuredElement:="684"] if (CheckDebug()) { key <- DatasetKey( domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = YEARS) ) ) ## This key is used later to extract stocks from the balanced session: ## For the new round where the starting year was no longer 2014 a discrepancy came out in the bal session between opening stocks of the ## first year of compilation. It was the decided to start the stock computation from the data present in the balanced session instead of the ## unbalanced ( and keep the stocks discrepancy in the unbalanced session instead). Liva and Cristina key_stocks_balanced <- DatasetKey( domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = c("5113","5071")), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = YEARS) ) ) } else { key <- swsContext.datasets[[2]] key@dimensions$timePointYears@keys <- YEARS key@dimensions$measuredItemFbsSua@keys <- itemKeys key@dimensions$measuredElementSuaFbs@keys <- elemKeys key@dimensions$geographicAreaM49@keys <- COUNTRY ##key for the stocks # key_stocks_balanced <- swsContext.datasets[[1]] key_stocks_balanced@dimensions$timePointYears@keys <- YEARS key_stocks_balanced@dimensions$measuredItemFbsSua@keys <- itemKeys key_stocks_balanced@dimensions$measuredElementSuaFbs@keys <- c("5113","5071") key_stocks_balanced@dimensions$geographicAreaM49@keys <- COUNTRY } dbg_print("download data") # LOAD data <- GetData(key) # Remove item that is not part of agriculture domain data <- data[measuredItemFbsSua != "F1223"] #LOAD stocks data from balanced session data_stock_balanced <- GetData(key_stocks_balanced) dbg_print("convert sugar") ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## data <- convertSugarCodes_new(data) #################### FODDER CROPS ########################################## # TODO: create SWS datatable for this. # Some of these items may be missing in reference files, # thus we carry forward the last observation. fodder_crops_items <- tibble::tribble( ~description, ~code, "Maize for forage", "01911", "Alfalfa for forage", "01912", "Sorghum for forage", "01919.01", "Rye grass for forage", "01919.02", "Other grasses for forage", "01919.91", "Clover for forage", "01919.03", "Other oilseeds for forage", "01919.94", "Other legumes for forage", "01919.92", "Cabbage for fodder", "01919.04", "Mixed grass and legumes for forage", "01919.93", "Turnips for fodder", "01919.05", "Beets for fodder", "01919.06", "Carrots for fodder", "01919.07", "Swedes for fodder", "01919.08", "Other forage products, nes", "01919.96", "Other forage crops, nes", "01919.95", "Hay for forage, from legumes", "01919.10", "Hay for forage, from grasses", "01919.09", "Hay for forage, from other crops nes", "01919.11" ) fodder_crops_availab <- data[ measuredItemFbsSua %chin% fodder_crops_items$code & measuredElementSuaFbs == "5510" ] if (nrow(fodder_crops_availab) > 0) { fodder_crops_complete <- CJ( geographicAreaM49 = unique(fodder_crops_availab$geographicAreaM49), measuredElementSuaFbs = "5510", timePointYears = unique(data$timePointYears), measuredItemFbsSua = unique(fodder_crops_availab$measuredItemFbsSua) ) fodder_crops_complete <- fodder_crops_complete[order(geographicAreaM49, measuredItemFbsSua, timePointYears)] fodder_crops <- dt_left_join( fodder_crops_complete, fodder_crops_availab[, .(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)], by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears") ) fodder_crops[, Value := zoo::na.locf(Value), by = c("geographicAreaM49", "measuredItemFbsSua") ] fodder_crops_new <- fodder_crops[ !fodder_crops_availab, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears") ] if (nrow(fodder_crops_new) > 0) { fodder_crops_new[, `:=`(flagObservationStatus = "E", flagMethod = "t")] data <- rbind(data, fodder_crops_new) } } #################### / FODDER CROPS ######################################## # opening_stocks_2014 <- # ReadDatatable( # "opening_stocks_2014", # where = paste0("m49_code IN (", # paste(shQuote(COUNTRY, type = "sh"), collapse = ", "), ")") # ) # The procedure works even if no previous opening stocks exists, but in that # case there is no way to know if data does not exist because there was an # issue downloading data or because it actually does not exist. Luckily there # are many calls to SWS, which should fail if there are issues: it is unlikely # that only this one fails. #stopifnot(nrow(opening_stocks_2014) > 0) message("Line 1286") non_null_prev_deltas <- unique( data[ measuredElementSuaFbs == "5071" & timePointYears %in% (startYear-5):(startYear-1) ][, .SD[sum(!dplyr::near(Value, 0)) > 0], by = c("geographicAreaM49", "measuredItemFbsSua") ][, .(geographicAreaM49, measuredItemFbsSua) ] ) # # # Keep only those for which recent variations are available # opening_stocks_2014 <- # opening_stocks_2014[ # non_null_prev_deltas, # on = c("geographicAreaM49", "measuredItemFbsSua"), # nomatch = 0 # ] # # The opening stock in the first year is computed as Opening stock t-1 + stock variation t-1 (giulia) original_opening_stocks <- data_stock_balanced[measuredElementSuaFbs %in% c("5113", "5071") ] #flagValidTable_stocks <- copy(flagValidTable) flagValidTable[is.na(flagObservationStatus), flagObservationStatus := ""] original_opening_stocks <- flagValidTable[ original_opening_stocks, on = c("flagObservationStatus", "flagMethod") ][, Valid := NULL ] unbal_protected_opening_stocks <- data[measuredElementSuaFbs %in% c("5113", "5071") ] unbal_protected_opening_stocks <- flagValidTable[ unbal_protected_opening_stocks, on = c("flagObservationStatus", "flagMethod") ][, Valid := NULL ] unbal_protected_opening_stocks <- unbal_protected_opening_stocks[Protected == TRUE,] original_opening_stocks<- rbind(original_opening_stocks[! unbal_protected_opening_stocks , on = c("measuredElementSuaFbs","geographicAreaM49", "timePointYears", "measuredItemFbsSua")], unbal_protected_opening_stocks) ## If starting of the previous year is NA is not working # StartingOpening<- original_opening_stocks[ , Op1Y:= Value[measuredElementSuaFbs=="5113" # & timePointYears==(startYear-1)] + Value[measuredElementSuaFbs=="5071" & timePointYears== (startYear-1)], # by= c("measuredItemFbsSua", "geographicAreaM49")] ## It has been decided to protect in general the opening stocks in 2014 original_opening_stocks[timePointYears %in% "2014" & measuredElementSuaFbs %in% "5113", Protected := TRUE] StartingOpening<- original_opening_stocks[ , Op1Y:= sum(Value[measuredElementSuaFbs=="5113" & timePointYears==(startYear-1)], Value[measuredElementSuaFbs=="5071" & timePointYears== (startYear-1)], na.rm = T), by= c("measuredItemFbsSua", "geographicAreaM49")] StartingOpening<- StartingOpening[measuredElementSuaFbs=="5113"] StartingOpening<-StartingOpening[!is.na(Op1Y)] StartingOpening[ , c("timePointYears", "Value", "flagObservationStatus", "flagMethod", "Protected", "measuredElementSuaFbs"):=NULL] StartingOpening<-unique(StartingOpening) # negative and positive limit StartingOpening[Op1Y < 0, Op1Y := 0] positivelimit <- data[ timePointYears == (startYear-1) & measuredItemFbsSua %in% unique(StartingOpening$measuredItemFbsSua) ][ ,opening_lim := sum( Value[measuredElementSuaFbs %chin% c("5510", "5610")], - Value[measuredElementSuaFbs == "5910"], na.rm = TRUE ) * 2, by = c("geographicAreaM49", "measuredItemFbsSua") ] positivelimit[ , c("measuredElementSuaFbs", "Value", "flagObservationStatus", "flagMethod", "timePointYears") := NULL] positivelimit<- as.data.table(unique(positivelimit)) StartingOpening<-merge(StartingOpening,positivelimit, by= c("measuredItemFbsSua", "geographicAreaM49") ) # StartingOpening[opening_lim<0, opening_lim:=0] StartingOpening$opening_lim <- as.integer(StartingOpening$opening_lim) # StartingOpening[opening_lim > 0 & Op1Y > opening_lim, Op1Y := opening_lim] StartingOpening[ , opening_lim:= NULL] original_opening_stocks<- original_opening_stocks[ measuredElementSuaFbs=="5113"] original_opening_stocks[ , Op1Y:=NULL] StartingOpening[ , timePointYears:= as.character(startYear)] # remove the opening that are protected in all opening stocks StartingOpening <- StartingOpening[ !original_opening_stocks[ timePointYears == startYear & Protected == TRUE, .(geographicAreaM49, measuredItemFbsSua) ], on = c("geographicAreaM49", "measuredItemFbsSua") ] all_opening_stocks <- merge( original_opening_stocks, StartingOpening, by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), all = TRUE ) all_opening_stocks[ !Protected %in% TRUE & !is.na(Op1Y), `:=`( Value = Op1Y, flagObservationStatus = "I", flagMethod = "-", # We protect these, in any case, because they should not # be overwritten, even if not (semi) official or expert Protected = TRUE, measuredElementSuaFbs = "5113", timePointYears = as.character(startYear) ) ][, Op1Y := NULL ] # # Remove protected in 2014 from cumulated # opening_stocks_2014 <- # opening_stocks_2014[ # !original_opening_stocks[ # timePointYears == "2014" & Protected == TRUE, # .(geographicAreaM49, measuredItemFbsSua) # ], # on = c("geographicAreaM49", "measuredItemFbsSua") # ] # # all_opening_stocks <- # merge( # original_opening_stocks, # opening_stocks_2014, # by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), # all = TRUE # ) # all_opening_stocks[ # !Protected %in% TRUE & is.na(Value) & !is.na(Value_cumulated), # `:=`( # Value = Value_cumulated, # flagObservationStatus = "I", # flagMethod = "-", # # We protect these, in any case, because they should not # # be overwritten, even if not (semi) official or expert # Protected = TRUE, # measuredElementSuaFbs = "5113", # timePointYears = "2014" # ) # ][, # Value_cumulated := NULL # ] ## remaining_opening_stocks have been commented since in the new round we don't create opening as 20% of the year before if the item is stockable ## otherwise the risk is to create stocks where stock does not exist before livia and cristina # Now, for all remaining stockable items, we create opening # stocks in 2014 as 20% of supply in 2013 (they should be 0 now, giulia) # remaining_opening_stocks <- # data[ # timePointYears == as.character(startYear-1) & # measuredItemFbsSua %chin% # setdiff( # stockable_items, # all_opening_stocks$measuredItemFbsSua # ) # ][, # .( # opening_20 = # sum( # Value[measuredElementSuaFbs %chin% c("5510", "5610")], # - Value[measuredElementSuaFbs == "5910"], # na.rm = TRUE # ) * 0.2, # timePointYears = as.character(startYear) # ), # by = c("geographicAreaM49", "measuredItemFbsSua") # ] # # remaining_opening_stocks[opening_20 < 0, opening_20 := 0] # # all_opening_stocks <- # merge( # all_opening_stocks, # remaining_opening_stocks, # by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), # all = TRUE # ) # # all_opening_stocks <- all_opening_stocks[!is.na(timePointYears)] # # all_opening_stocks[ # !Protected %in% TRUE & is.na(Value) & !is.na(opening_20), # `:=`( # Value = opening_20, # flagObservationStatus = "I", # flagMethod = "i", # # We protect these, in any case, because they should not # # be overwritten, even if not (semi) official or expert # Protected = TRUE # ) # ][, # opening_20 := NULL # ] # to add: delete automatically opening stock for non-stockable commodity, even if they have time-series. giulia complete_all_opening <- CJ( geographicAreaM49 = unique(all_opening_stocks$geographicAreaM49), timePointYears = as.character(min(all_opening_stocks$timePointYears):endYear), measuredItemFbsSua = unique(all_opening_stocks$measuredItemFbsSua) ) all_opening_stocks <- merge( complete_all_opening, all_opening_stocks, by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), all = TRUE ) all_opening_stocks[, orig_val := Value] all_opening_stocks <- all_opening_stocks[!is.na(Value)][ all_opening_stocks, on = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), roll = Inf] all_opening_stocks[ is.na(orig_val) & !is.na(Value), `:=`( Protected = FALSE, flagObservationStatus = "E", flagMethod = "t" ) ] all_opening_stocks[, measuredElementSuaFbs := "5113"] all_opening_stocks[, orig_val := NULL] all_opening_stocks[, names(all_opening_stocks)[grep("^i\\.", names(all_opening_stocks))] := NULL] all_opening_stocks <- all_opening_stocks[!is.na(timePointYears)] # Generate stocks variations for items for which opening # exists for ALL years and variations don't exist opening_avail_all_years <- all_opening_stocks[ !is.na(Value) & timePointYears >= startYear, .SD[.N == (endYear - startYear + 1)], measuredItemFbsSua ] delta_avail_for_open_all_years <- data[ measuredElementSuaFbs == "5071" & timePointYears >= startYear & measuredItemFbsSua %chin% opening_avail_all_years$measuredItemFbsSua, .SD[.N == (endYear - startYear + 1)], measuredItemFbsSua ] to_generate_by_ident <- setdiff( opening_avail_all_years$measuredItemFbsSua, delta_avail_for_open_all_years$measuredItemFbsSua ) data_rm_ident <- data[measuredElementSuaFbs == "5071" & measuredItemFbsSua %chin% to_generate_by_ident] if (length(to_generate_by_ident) > 0) { opening_avail_all_years <- opening_avail_all_years[measuredItemFbsSua %chin% to_generate_by_ident] opening_avail_all_years[, Protected := NULL] next_opening_key <- DatasetKey( domain = "Stock", dataset = "stocksdata", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = "5113"), measuredItemFbsSua = Dimension(name = "measuredItemCPC", keys = unique(opening_avail_all_years$measuredItemFbsSua)), timePointYears = Dimension(name = "timePointYears", keys = as.character(as.numeric(max(opening_avail_all_years$timePointYears)) + 1)) ) ) next_opening <- GetData(next_opening_key) setnames( next_opening, c("measuredItemCPC", "measuredElement"), c("measuredItemFbsSua", "measuredElementSuaFbs") ) opening_avail_all_years <- rbind(opening_avail_all_years, next_opening) opening_avail_all_years <- opening_avail_all_years[ order(geographicAreaM49, measuredItemFbsSua, timePointYears) ] opening_avail_all_years[, delta := shift(Value, type = "lead") - Value, by = c("geographicAreaM49", "measuredItemFbsSua") ] opening_avail_all_years[, delta := ifelse( timePointYears == max(timePointYears) & is.na(delta), 0, delta ), by = c("geographicAreaM49", "measuredItemFbsSua") ] opening_avail_all_years <- dt_left_join( opening_avail_all_years, flagValidTable, by = c("flagObservationStatus", "flagMethod") ) opening_avail_all_years[shift(Protected, type = "lead") == TRUE & Protected == TRUE, `:=`(delta_flag_obs = "T", delta_flag_method = "p")] opening_avail_all_years[!(shift(Protected, type = "lead") == TRUE & Protected == TRUE), `:=`(delta_flag_obs = "I", delta_flag_method = "i")] delta_identity <- opening_avail_all_years[ timePointYears %in% yearVals, .( geographicAreaM49, measuredItemFbsSua, timePointYears, measuredElementSuaFbs = "5071", Value = delta, flagObservationStatus = delta_flag_obs, flagMethod = delta_flag_method ) ] delta_identity <- delta_identity[!data_rm_ident, on = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears")] data <- rbind(data, delta_identity) data <- data[order(geographicAreaM49, measuredItemFbsSua, timePointYears, measuredElementSuaFbs)] } # / Generate stocks variations for items for which opening # / exists for ALL years and variations don't exist # Recalculate opening stocks data_for_opening <- dt_left_join( all_opening_stocks[, .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, new_opening = Value) ], data[ measuredElementSuaFbs == '5071' & timePointYears %in% yearVals & !is.na(Value), .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, delta = Value) ], by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data_for_opening[is.na(delta), delta := 0] data_for_opening <- data_for_opening[timePointYears >= startYear] data_for_opening <- update_opening_stocks(data_for_opening) all_opening_stocks <- dt_left_join( all_opening_stocks, data_for_opening[, .( geographicAreaM49, measuredItemFbsSua = measuredItemSuaFbs, timePointYears, new_opening ) ], by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ) all_opening_stocks[ !is.na(new_opening) & (round(new_opening) != round(Value) | is.na(Value)), `:=`( Value = new_opening, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] all_opening_stocks[, new_opening := NULL] # / Recalculate opening stocks data <- dt_left_join(data, flagValidTable, by = c("flagObservationStatus", "flagMethod")) data[flagObservationStatus %chin% c("", "T"), `:=`(Official = TRUE, Protected = TRUE)] data[is.na(Official), Official := FALSE] data[is.na(Protected), Protected := FALSE] # We remove "5113" (opening stocks) as will be stored in separate table. data <- data[measuredElementSuaFbs != "5113"] dbg_print("elementToCodeNames") # XXX FIXME: the elementCodesToNames below is # not working proberply, see issue #38 codes <- as.data.table(tibble::tribble( ~measuredElementSuaFbs, ~name, "5910", "exports", "5520", "feed", "5141", "food", "5023", "foodManufacturing", "5610", "imports", "5165", "industrial", "5016", "loss", "5510", "production", "5525", "seed", "5164", "tourist", "5071", "stockChange" )) data <- dt_left_join(data, codes, by = "measuredElementSuaFbs") data[, measuredElementSuaFbs := name] data[, name := NULL] # NOTE: if this should be used again (#38), camelCase the element names (#45) #data <- # elementCodesToNames( # data, # itemCol = "measuredItemFbsSua", # elementCol = "measuredElementSuaFbs" # ) # XXX: there are some NAs here, but probably there shouldn't data <- data[!is.na(measuredElementSuaFbs)] setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") message("Line 1686") ########## Remove feed if new element and negative imbalance is huge # Feed requires country-specific reference files, which are being updated. # Until these get reviewed, the feed module will generate feed items in # some countries, where it is not required/needed/appropriate. Below, we # remove the NEW feed item if the NEGATIVE imbalance obtained by including # it is more than 50% of supply (e.g., -72%). new_feed <- data[ measuredElementSuaFbs == "feed", .( pre = sum(!is.na(Value[timePointYears < startYear])), post = sum(!is.na(Value[timePointYears >= startYear])) ), by = c("geographicAreaM49", "measuredItemSuaFbs") ][ pre == 0 & post > 0 ][, c("pre", "post") := NULL ] msg_new_feed_remove <- "No NEW feed removed" msg_new_feed_dubious <- "No other NEW items should be removed" if (nrow(new_feed) > 0) { # prev_data_avg <- # data[ # new_feed, on = c("geographicAreaM49", "measuredItemSuaFbs") # ][ # timePointYears >= 2010 & timePointYears < startYear # ][ # order(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears), # Value := na.fill_(Value), # by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") # ][, # .(Value = sum(Value) / sum(!is.na(Value)), timePointYears = 0), # by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") # ] # # calculateImbalance(prev_data_avg, supply_subtract = c("exports", "stockChange")) # prev_processed_avg <- # prev_data_avg[ # supply > 0 & # utilizations > 0 & # measuredElementSuaFbs == "foodManufacturing" & # !is.na(Value), # .(geographicAreaM49, measuredItemSuaFbs, proc_ratio = Value / supply) # ] new_data_avg <- data[ new_feed, on = c("geographicAreaM49", "measuredItemSuaFbs") ][ # measuredElementSuaFbs != "foodManufacturing" & timePointYears >= 2014 ][ order(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears), Value := na.fill_(Value), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ][, .(Value = sum(Value) / sum(!is.na(Value) & !dplyr::near(Value, 0)), timePointYears = 1), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ][ !is.nan(Value) ] calculateImbalance( new_data_avg, keep_utilizations = FALSE, supply_subtract = c("exports", "stockChange") ) # new_data_supply <- # unique( # new_data_avg[, # c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "supply"), # with = FALSE # ] # ) # new_data_proc <- # dt_left_join( # new_data_supply, # prev_processed_avg, # by = c("geographicAreaM49", "measuredItemSuaFbs"), # nomatch = 0 # ) # # new_data_proc <- # new_data_proc[ # supply > 0, # .(geographicAreaM49, measuredItemSuaFbs, # measuredElementSuaFbs = "foodManufacturing", # Value = supply * proc_ratio, timePointYears = 1) # ] # # new_data_avg[, c("supply", "imbalance") := NULL] # new_data_avg <- # rbind( # new_data_avg, # new_data_proc # ) # # calculateImbalance(new_data_avg, supply_subtract = c("exports", "stockChange")) new_feed_to_remove <- unique( new_data_avg[ imbalance / supply <= -0.3, c("geographicAreaM49", "measuredItemSuaFbs"), with = FALSE ] ) new_feed_to_remove[, measuredElementSuaFbs := "feed"] new_feed_to_remove[, remove_feed := TRUE] new_feed_dubious <- unique( new_data_avg[ imbalance / supply > -0.3 & imbalance / supply <= -0.05, .(geographicAreaM49, measuredItemSuaFbs, x = imbalance / supply) ][order(x)][, x := NULL] ) data <- merge( data, new_feed_to_remove, by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs"), all.x = TRUE ) feed_to_remove <- data[ remove_feed == TRUE & Protected == FALSE ][, .(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears) ] data[, remove_feed := NULL] data <- data[!feed_to_remove, on = names(feed_to_remove)] if (nrow(feed_to_remove) > 0) { msg_new_feed_remove <- paste(new_feed_to_remove$measuredItemSuaFbs, collapse = ", ") } if (nrow(new_feed_dubious) > 0) { msg_new_feed_dubious <- paste(new_feed_dubious$measuredItemSuaFbs, collapse = ", ") } } ########## / Remove feed if new element and negative imbalance is huge treeRestricted <- tree[, c("measuredItemParentCPC", "measuredItemChildCPC", "processingLevel"), with = FALSE ] treeRestricted <- unique(treeRestricted[order(measuredItemChildCPC)]) primaryInvolved <- faoswsProduction::getPrimary(processedCPC, treeRestricted, p) dbg_print("primary involved descendents") # XXX: check here, 0111 is in results primaryInvolvedDescendents <- getChildren( commodityTree = treeRestricted, parentColname = "measuredItemParentCPC", childColname = "measuredItemChildCPC", topNodes = primaryInvolved ) # stocks need to be generated for those items for # which "opening stocks" are available items_to_generate_stocks <- unique(all_opening_stocks$measuredItemFbsSua) stock <- CJ( measuredItemSuaFbs = items_to_generate_stocks, measuredElementSuaFbs = 'stockChange', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears) ) # rbind with anti_join data <- rbind( data, stock[!data, on = c('measuredItemSuaFbs', 'measuredElementSuaFbs', 'geographicAreaM49', 'timePointYears')], fill = TRUE ) # XXX what is primaryInvolvedDescendents ????????? #deriv <- CJ(measuredItemSuaFbs = primaryInvolvedDescendents, measuredElementSuaFbs = 'production', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears)) deriv <- CJ( measuredItemSuaFbs = unique(tree$measuredItemChildCPC), measuredElementSuaFbs = 'production', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears) ) # rbind with anti_join data <- rbind( data, deriv[!data, on = c('measuredItemSuaFbs', 'measuredElementSuaFbs', 'geographicAreaM49', 'timePointYears')], fill = TRUE ) data[is.na(Official), Official := FALSE] data[is.na(Protected), Protected := FALSE] data[, stockable := measuredItemSuaFbs %chin% stockable_items] # XXX: Remove items for which no production, imports or exports exist after 2013. non_existing_for_imputation <- setdiff( data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports') & timePointYears < startYear, unique(measuredItemSuaFbs) ], data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports') & timePointYears >= startYear, unique(measuredItemSuaFbs) ] ) data <- data[!(measuredItemSuaFbs %chin% non_existing_for_imputation)] message("Line 1943") ############################################### Create derived production ################################### dbg_print("derivation of shareDownUp") ############# ShareDownUp ---------------------------------------- #this table will be used to assign to zeroweight comodities #the processed quantities of their coproduct coproduct_table <- ReadDatatable('zeroweight_coproducts') stopifnot(nrow(coproduct_table) > 0) # Can't do anything if this information if missing, so remove these cases coproduct_table <- coproduct_table[!is.na(branch)] ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ### XXX removing these cases as '22242.01' appears as zero-weight XXXX ### XXX for main product = '22110.04' Buffalo milk XXXX ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX coproduct_table <- coproduct_table[branch != '22242.01 + 22110.04'] coproduct_table <- coproduct_table[, .(measured_item_child_cpc, branch)] coproduct_for_sharedownup <- copy(coproduct_table) coproduct_for_sharedownup_easy <- coproduct_for_sharedownup[!grepl('\\+|or', branch)] coproduct_for_sharedownup_plus <- coproduct_for_sharedownup[grepl('\\+', branch)] coproduct_for_sharedownup_plus <- rbind( tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_plus <- unique(coproduct_for_sharedownup_plus) coproduct_for_sharedownup_or <- coproduct_for_sharedownup[grepl('or', branch)] coproduct_for_sharedownup_or <- rbind( #coproduct_table_or, tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_or <- unique(coproduct_for_sharedownup_or) coproduct_for_sharedownup <- rbind( coproduct_for_sharedownup_easy, coproduct_for_sharedownup_plus, coproduct_for_sharedownup_or ) ## solve the problem of wrong connection (raw centrifugal sugar --> bagasse towards raw cane and beet --> bagasse) coproduct_for_sharedownup[measured_item_child_cpc == "39140.02" & branch == "23511.01", branch := "2351f"] #Using the whole tree not by level ExtrRate <- tree[ !is.na(Value) & measuredElementSuaFbs == 'extractionRate' ][, .( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value, processingLevel ) ] # We include utilizations to identify if proceseed is the only utilization data_tree <- data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange', 'foodManufacturing', 'loss', 'food', 'industrial', 'feed', 'seed') ] #subset the tree according to parents and child present in the SUA data ExtrRate <- ExtrRate[ measuredItemChildCPC %chin% data_tree$measuredItemSuaFbs & measuredItemParentCPC %chin% data_tree$measuredItemSuaFbs ] setnames(data_tree, "measuredItemSuaFbs", "measuredItemParentCPC") dataProcessingShare<-copy(data_tree) data_tree <- merge( data_tree, ExtrRate, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE, all.y = TRUE ) data_tree <- as.data.table(data_tree) # the availability for parent that have one child and only processed as utilization will # be entirely assigned to processed for that its unique child even for 2014 onwards data_tree[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ] data_tree[availability<0,availability:=0] # used to chack if a parent has processed as utilization data_tree[, proc_Median := median( Value[measuredElementSuaFbs == "foodManufacturing" & timePointYears %in% 2000:endYear], na.rm=TRUE ), by = c(p$parentVar, p$geoVar) ] # boolean variable taking TRUE if the parent has only processed as utilization data_tree[, unique_proc := proc_Median > 0 & !is.na(proc_Median) & # ... is the only utilization all(is.na(Value[!(measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange','foodManufacturing'))])), by = c(p$parentVar, p$geoVar, p$yearVar) ] sel_vars <- c("measuredItemParentCPC", "geographicAreaM49", "timePointYears", "measuredElementSuaFbs", "flagObservationStatus", "flagMethod", "Value", "Official", "measuredItemChildCPC", "extractionRate", "processingLevel") data_tree<- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) message("Line 2118") # dataset to calculate the number of parent of each child and the number of children of each parent # including zeroweight commodities sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC","timePointYears") data_count <- unique(data_tree[, sel_vars, with = FALSE], by = sel_vars) #Caculate the number of parent of each child data_count[, number_of_parent := .N, by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # calculate the number of children of each parent # we exclude zeroweight to avoid doublecounting of children (processing) data_count[measuredItemChildCPC %!in% zeroWeight, number_of_children := uniqueN(measuredItemChildCPC), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree <- dt_left_join( data_tree, data_count, by = c(p$parentVar, p$childVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) # dataset containing the processed quantity of parents food_proc <- unique( data_tree[ measuredElementSuaFbs == "foodManufacturing", c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value"), with = FALSE ], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value") ) setnames(food_proc, "Value", "parent_qty_processed") food_proc[timePointYears >= startYear, parent_qty_processed := NA_real_] data_tree <- dt_left_join( data_tree, food_proc, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "extractionRate", "parent_qty_processed", "processingLevel", "number_of_parent", "number_of_children") data_tree <- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) # dataset containing the production of child commodities dataprodchild <- data[measuredElementSuaFbs %chin% c('production')] setnames(dataprodchild, "measuredItemSuaFbs", "measuredItemChildCPC") dataprodchild <- unique( dataprodchild[, c("geographicAreaM49", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] ) setnames(dataprodchild, "Value", "production_of_child") message("Line 2200") dataprodchild[timePointYears >= startYear, production_of_child := NA_real_] data_tree <- dt_left_join( data_tree, dataprodchild, by = c(p$geoVar, p$childVar, p$yearVar) ) # ShareDownups for zeroweights are calculated separately # to avoid double counting when agregating processed quantities of parent # dataset containing informations of zeroweight commodities data_zeroweight <- data_tree[measuredItemChildCPC %chin% zeroWeight] # import data for coproduct relation zw_coproduct <- coproduct_for_sharedownup[, .(zeroweight = measured_item_child_cpc, measuredItemChildCPC = branch) ] zw_coproduct <- unique(zw_coproduct, by = c("measuredItemChildCPC", "zeroweight")) # We subset the zeroweight coproduct reference table by taking only zeroweights and their coproduct # that are childcommodities in the tree of the country zw_coproduct <- zw_coproduct[ measuredItemChildCPC %chin% data_tree$measuredItemChildCPC & zeroweight %chin% data_tree$measuredItemChildCPC ] # Computing information for non zeroweight commodities data_tree <- data_tree[measuredItemChildCPC %!in% zeroWeight] # this dataset will be used when creating processing share and shareUpdown dataComplete <- copy(data_tree) # Quantity of parent destined to the production of the given child (only for child with one parent for the moment) (to delete?) data_tree[, processed_to_child := ifelse(number_of_parent == 1, production_of_child, NA_real_)] # if a parent has one child, all the processed goes to that child data_tree[ number_of_children == 1, processed_to_child := parent_qty_processed * extractionRate, processed_to_child ] data_tree[production_of_child == 0, processed_to_child := 0] # assigning the entired availability to processed for parent having only processed as utilization data_tree[ number_of_children == 1 & unique_proc == TRUE, processed_to_child := availability * extractionRate ] # mirror assignment for imputing processed quantity for multple parent children # 5 loop is sufficient to deal with all the cases for (k in 1:5) { data_tree <- RemainingToProcessedParent(data_tree) data_tree <- RemainingProdChildToAssign(data_tree) } data_tree <- RemainingToProcessedParent(data_tree) # proportional allocation of the remaing production of multiple parent children data_tree[, processed_to_child := ifelse( number_of_parent > 1 & is.na(processed_to_child), (remaining_to_process_child * is.na(processed_to_child) * remaining_processed_parent) / sum((remaining_processed_parent * is.na(processed_to_child)), na.rm = TRUE), processed_to_child), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # Update of remaining production to assing ( should be zero for 2000:2013) data_tree[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate,na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data_tree[ remaining_processed_parent < 0, remaining_processed_parent := 0 ] # Impute processed quantity for 2014 onwards using 3 years average # (this only to imput shareDownUp) data_tree <- data_tree[ order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), processed_to_child_avg := rollavg(processed_to_child, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") ] setkey(data_tree, NULL) data_tree[timePointYears >= startYear & is.na(processed_to_child), processed_to_child := processed_to_child_avg] # Back to zeroweight cases(we assign to zeroweights the processed quantity of their coproduct(already calculated)) zw_coproduct_bis <- merge( data_tree, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) zw_coproduct_bis[, `:=`( measuredItemChildCPC = zeroweight, processed_to_child = processed_to_child / extractionRate ) ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") zw_coproduct_bis <- zw_coproduct_bis[, c(sel_vars, "processed_to_child"), with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk zw_coproduct_bis[, processed_to_child := sum(processed_to_child, na.rm = TRUE), by = sel_vars ] zw_coproduct_bis <- unique(zw_coproduct_bis, by = colnames(zw_coproduct_bis)) data_zeroweight <- dt_left_join(data_zeroweight, zw_coproduct_bis, by = sel_vars) data_zeroweight[, processed_to_child := processed_to_child * extractionRate ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "number_of_parent", "parent_qty_processed", "production_of_child", "processed_to_child") data_zeroweight <- data_zeroweight[, sel_vars, with = FALSE] data_tree <- data_tree[, sel_vars, with = FALSE] #combining zeroweight and non zero weight commodities data_tree <- rbind(data_tree, data_zeroweight) #calculate ShareDownUp data_tree[, shareDownUp := processed_to_child / sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] #some corrections... data_tree[is.na(shareDownUp) & number_of_parent == 1, shareDownUp := 1] data_tree[ (production_of_child == 0 | is.na(production_of_child)) & measuredItemChildCPC %!in% zeroWeight & timePointYears < startYear, shareDownUp := 0 ] data_tree[ (parent_qty_processed == 0 | is.na(parent_qty_processed)) & timePointYears < startYear, shareDownUp :=0 ] data_tree[is.na(shareDownUp), shareDownUp := 0] data_tree <- unique( data_tree[, c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "shareDownUp"), with = FALSE ] ) ########################GENERARING ProcessedShare for parent---------------------------------------- ######################## ANd ShareUpDown for children ############################################## #################################################################################################### dataProcessingShare[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), #by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) by = c(p$geoVar, p$yearVar, p$parentVar) ] dataProcessingShare[,SumLoss:=sum( Value[measuredElementSuaFbs=="loss" & timePointYears %in% yearVals],na.rm = TRUE ), by=c("geographicAreaM49","measuredItemParentCPC") ] dataProcessingShare[,SumProd:=sum( Value[measuredElementSuaFbs=="production" & timePointYears %in% yearVals],na.rm = TRUE ), by=c("geographicAreaM49","measuredItemParentCPC") ] dataProcessingShare[,parent_qty_processed:=Value[measuredElementSuaFbs=="foodManufacturing"], by=c("geographicAreaM49","measuredItemParentCPC","timePointYears") ] dataProcessingShare[,Prod:=Value[measuredElementSuaFbs=="production"], by=c("geographicAreaM49","measuredItemParentCPC","timePointYears") ] dataProcessingShare[,RatioLoss:=SumLoss/SumProd] dataProcessingShare[, loss_Median_before := median( Value[measuredElementSuaFbs == "loss" & timePointYears %in% 2000:(startYear-1)], na.rm=TRUE ), by = c(p$parentVar, p$geoVar) ] dataProcessingShare[,NewLoss:=ifelse((is.na(loss_Median_before)|loss_Median_before==0) & !is.na(RatioLoss),TRUE,FALSE)] # dataProcessingShare[, # NewLoss := # # have loss for 2014-2018 & ... # !is.na(RatioLoss)& # # does not have past losses & # is.na(loss_Median_before) & # # ... loss,process and tourist are the only utilization # all(is.na(Value[!(measuredElementSuaFbs %chin% # c('loss', 'production', 'imports', # 'exports', 'stockChange','foodManufacturing', 'tourist'))])), # by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") # ] # dataset containing the processed quantity of parents dataProcessingShare <- unique( dataProcessingShare[, c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Prod", "availability","RatioLoss","NewLoss","parent_qty_processed"), with = FALSE ], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Prod", "availability","RatioLoss","NewLoss","parent_qty_processed") ) #setnames(dataProcessingShare, "Value", "Prod") # Processing share and ShareUpDown dataProcessingShare <- unique( dataProcessingShare[, c("geographicAreaM49", "timePointYears", "availability", "measuredItemParentCPC", "parent_qty_processed", "RatioLoss","NewLoss","Prod"), with = FALSE ], by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "parent_qty_processed") ) dataProcessingShare[timePointYears %in% yearVals, parent_qty_processed := NA_real_] #correction of Pshare to adjust processed in case of new Loss dataProcessingShare[is.na(RatioLoss),RatioLoss:=0] dataProcessingShare[is.na(Prod),Prod:=0] # dataProcessingShare[, # Pshare := ifelse(NewLoss==TRUE,(parent_qty_processed-RatioLoss*Prod) / availability, # parent_qty_processed / availability), # by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") # ] dataProcessingShare[, Pshare := parent_qty_processed / availability, by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] dataProcessingShare[Pshare > 1, Pshare := 1] dataProcessingShare[Pshare < 0,Pshare := 0] dataProcessingShare[is.nan(Pshare), Pshare := NA_real_] dataProcessingShare <- dataProcessingShare[ order(geographicAreaM49, measuredItemParentCPC, timePointYears), Pshare_avr := rollavg(Pshare, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC") ] setkey(dataProcessingShare, NULL) # we estimate Pshare for 2014 onwards, even if processed are modified manually because a this stage # availability of 2014 onwards are known (stocks are not generated yet) dataProcessingShare[timePointYears >= startYear, Pshare := Pshare_avr] dataProcessingShare[, Pshare_avr := NULL] data_Pshare <- dataProcessingShare[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "parent_qty_processed", "Pshare","NewLoss"), with = FALSE ] data_Pshare<-merge( data_Pshare, data[measuredElementSuaFbs=="loss",list(geographicAreaM49,timePointYears,measuredItemParentCPC=measuredItemSuaFbs,Loss=Value)], by=c(p$geoVar,p$parentVar,p$yearVar), all.x = TRUE ) # calculating shareUpdown for each child data_ShareUpDoawn <- dataComplete[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "parent_qty_processed", "measuredItemChildCPC", "extractionRate", "production_of_child", "number_of_children"), with = FALSE ] data_ShareUpDoawn <- unique( data_ShareUpDoawn, by = colnames(data_ShareUpDoawn) ) data_ShareUpDoawn <- merge( data_ShareUpDoawn, data_tree, by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), all = TRUE ) data_ShareUpDoawn <- data_ShareUpDoawn[measuredItemChildCPC %!in% zeroWeight] data_ShareUpDoawn[, shareUpDown := NA_real_] data_ShareUpDoawn[ !is.na(parent_qty_processed) & extractionRate>0, shareUpDown := (production_of_child / extractionRate) * shareDownUp / sum(production_of_child / extractionRate * shareDownUp, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] data_ShareUpDoawn[is.nan(shareUpDown), shareUpDown := NA_real_] data_ShareUpDoawn <- data_ShareUpDoawn[ order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), shareUpDown_avg := rollavg(shareUpDown, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") ] setkey(data_ShareUpDoawn, NULL) data_ShareUpDoawn[timePointYears >= startYear, shareUpDown := shareUpDown_avg] data_ShareUpDoawn[, shareUpDown_avg := NULL] data_ShareUpDoawn[ timePointYears >= startYear, shareUpDown := shareUpDown / sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "shareUpDown") data_ShareUpDoawn_final <- data_ShareUpDoawn[, sel_vars, with = FALSE] shareUpDown_zeroweight <- merge( data_ShareUpDoawn_final, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) shareUpDown_zeroweight[, measuredItemChildCPC := zeroweight] shareUpDown_zeroweight <- shareUpDown_zeroweight[, sel_vars, with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk shareUpDown_zeroweight<- shareUpDown_zeroweight[, shareUpDown := sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") ] shareUpDown_zeroweight <- unique( shareUpDown_zeroweight, by = colnames(shareUpDown_zeroweight) ) # /correction data_ShareUpDoawn_final <- rbind(data_ShareUpDoawn_final, shareUpDown_zeroweight) # some correction data_ShareUpDoawn_final[is.na(shareUpDown), shareUpDown := 0] data_ShareUpDoawn_final[!is.na(shareUpDown), flagObservationStatus := "I"] data_ShareUpDoawn_final[!is.na(shareUpDown), flagMethod := "c"] # sAVE DATA TO SWS shareUpDown_to_save <- copy(data_ShareUpDoawn_final) shareUpDown_to_save[, measuredElementSuaFbs := "5431"] setnames( shareUpDown_to_save, c("measuredItemParentCPC", "measuredItemChildCPC"), c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree") ) setnames(shareUpDown_to_save, "shareUpDown", "Value") #shareUpDown_to_save[, Value := round(Value, 3)] message("Line 2628") sessionKey_shareUpDown <- swsContext.datasets[[3]] CONFIG <- GetDatasetConfig(sessionKey_shareUpDown@domain, sessionKey_shareUpDown@dataset) data_shareUpDown_sws <- GetData(sessionKey_shareUpDown) data_shareUpDown_sws[ #timePointYears >= 2014 & ((measuredItemParentCPC_tree == "02211" & measuredItemChildCPC_tree == "22212") | #cheese from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC_tree == "22110.02" & measuredItemChildCPC_tree == "22251.01")), Value := 0 ] #saving ShareUpDown For the first time #all flage are (i,c) like production of derived if (nrow(data_shareUpDown_sws) == 0) { faosws::SaveData( domain = "suafbs", dataset = "up_down_share", data = shareUpDown_to_save, waitTimeout = 20000 ) } else { setnames( data_shareUpDown_sws, c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree", "Value"), c("measuredItemParentCPC", "measuredItemChildCPC", "shareUpDown") ) data_ShareUpDoawn_to_use <- copy(data_shareUpDown_sws) data_ShareUpDoawn_to_use <- data_ShareUpDoawn_to_use[, colnames(data_ShareUpDoawn_final), with = FALSE] data_ShareUpDoawn_final<-data_ShareUpDoawn_final[timePointYears %in% as.character(yearVals)] #If a new connection parent-child is added, the shareUpDown of all the children are affected #So we overwrite the share of all the children of the parent in the new connection new_connection<- data_ShareUpDoawn_final[!data_ShareUpDoawn_to_use, on = c('geographicAreaM49', 'measuredItemParentCPC', 'measuredItemChildCPC', 'timePointYears') ] # rbind with anti_join data_ShareUpDoawn_final <- rbind( data_ShareUpDoawn_to_use[!new_connection, #we exclude parent included in the new connection on = c('geographicAreaM49', 'measuredItemParentCPC', 'timePointYears')], unique( data_ShareUpDoawn_final[ unique(new_connection[,c('geographicAreaM49', 'measuredItemParentCPC', 'timePointYears'),with=FALSE]), on = c('geographicAreaM49', 'measuredItemParentCPC', 'timePointYears') ] ), fill = TRUE ) } #consistency check: sum of shareUpDown by parent should not exceed 1. message("Line 2690") data_ShareUpDoawn_final_invalid <- data_ShareUpDoawn_final[ measuredItemChildCPC %!in% zeroWeight, .(sum_shares = round(sum(shareUpDown, na.rm = TRUE),1)), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ][ !dplyr::near(sum_shares, 1) & !dplyr::near(sum_shares, 0) ] if (nrow(data_ShareUpDoawn_final_invalid) > 0) { write.csv( data_ShareUpDoawn_final_invalid, file.path(paste0("ShareUpDown_toCorrect_", COUNTRY, ".csv")) ) if (!CheckDebug()) { send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Some shareUpDown are invalid", body = c(paste("There are some invalid shareUpDown (they do not sum to 1). See attachment and fix them in the SWS shareUpDown dataset"), file.path(paste0("ShareUpDown_toCorrect_", COUNTRY, ".csv"))) ) } stop("Some shareUpDown can create conflict. Check your email.") } # # if(nrow(data_ShareUpDoawn_final)!=0){ # # # } #/processingShare--------------------- message("Line 2729") # / Tables that will be required by the co-product issue (fix processingShare) sessionKey_shareDownUp <- swsContext.datasets[[4]] CONFIG <- GetDatasetConfig(sessionKey_shareDownUp@domain, sessionKey_shareDownUp@dataset) data_shareDownUp_sws <- GetData(sessionKey_shareDownUp) ########### set parents present in sws and not present in the estimated data to zero ########### data_tree_test <- merge( data.table( geographicAreaM49 = unique(data_tree$geographicAreaM49), timePointYears = sort(unique(data_tree$timePointYears)) ), unique( data_shareDownUp_sws[, list(geographicAreaM49, measuredItemParentCPC = measuredItemParentCPC_tree, measuredItemChildCPC = measuredItemChildCPC_tree) ] ), by = "geographicAreaM49", all = TRUE, allow.cartesian = TRUE ) #not solved issue #diff_test <- data_tree[!data_tree_test, on = c("geographicAreaM49","measuredItemParentCPC", # "measuredItemChildCPC","timePointYears")] missing_connections <- data_tree_test[!data_tree, on = c("geographicAreaM49","measuredItemParentCPC", "measuredItemChildCPC","timePointYears")] missing_connections <- missing_connections[, shareDownUp := 0 ] missing_connections <- missing_connections[, list(geographicAreaM49,measuredItemParentCPC,measuredItemChildCPC, timePointYears,shareDownUp)] data_tree <- rbind(data_tree, missing_connections) #final sharedowmUp shareDownUp_previous <-copy(data_shareDownUp_sws) setnames(shareDownUp_previous,c("Value","measuredItemParentCPC_tree","measuredItemChildCPC_tree"), c("shareDownUp_prev","measuredItemParentCPC","measuredItemChildCPC")) if (nrow(shareDownUp_previous) > 0) { data_tree_final <- dt_left_join( data_tree, shareDownUp_previous, by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ) data_tree_final[flagObservationStatus == "E" & flagMethod=="f", shareDownUp := shareDownUp_prev] data_tree_final[!is.na(shareDownUp) & is.na(flagMethod),`:=`(flagObservationStatus="I", flagMethod="i", measuredElementSuaFbs="5432")] message("Line 2830") data_tree_final[, shareDownUp_prev := NULL] data_tree_final_save <- copy(data_tree_final) data_tree_final[,`:=`(measuredElementSuaFbs=NULL,flagObservationStatus=NULL,flagMethod=NULL)] data_tree_final <- unique(data_tree_final, by = colnames(data_tree_final)) } else { data_tree_final <- data_tree data_tree_final_save <- copy(data_tree_final) data_tree_final_save[,`:=`(flagObservationStatus="I", flagMethod="i", measuredElementSuaFbs="5432")] } data_tree_final_save<-data_tree_final_save[timePointYears %in% startYear:endYear] setnames(data_tree_final_save,c("measuredItemParentCPC","measuredItemChildCPC","shareDownUp"), c("measuredItemParentCPC_tree","measuredItemChildCPC_tree","Value")) faosws::SaveData( domain = "suafbs", dataset = "down_up_share", data = data_tree_final_save, waitTimeout = 20000 ) # Check on consistency of shareDownUp (computed + manual Ef in sws) shareDownUp_invalid <- data_tree_final[, .(sum_shares = round(sum(shareDownUp),1)), by = c("geographicAreaM49", "timePointYears", "measuredItemChildCPC") ][ !dplyr::near(sum_shares, 1) & !dplyr::near(sum_shares, 0) ][ timePointYears >= startYear ] if (nrow(shareDownUp_invalid) > 0) { shareDownUp_invalid <- data_tree_final[ shareDownUp_invalid, on = c("geographicAreaM49", "timePointYears", "measuredItemChildCPC") ] write.csv( shareDownUp_invalid, file.path(paste0("shareDownUp_INVALID_", COUNTRY, ".csv")) ) if (!CheckDebug()) { send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Some shareDownUp are invalid", body = c(paste("There are some invalid shareDownUp (they do not sum to 1). See attachment and fix them in", sub("/work/SWS_R_Share/", "", shareDownUp_file)), file.path(paste0("shareDownUp_INVALID_", COUNTRY, ".csv"))) ) } unlink(file.path(R_SWS_SHARE_PATH, USER, paste0("shareDownUp_INVALID_", COUNTRY, ".csv"))) stop("Some shares are invalid. Check your email.") } message("Line 2905") # / END ShareDownUp ------------------------------------------------------- # stockable items for which a historical series of at least # 5 non-missing/non-null data points exist historical_avail_stocks <- data[ measuredElementSuaFbs == "stockChange" & timePointYears < startYear & !is.na(Value) & stockable == TRUE, .(n = sum(!dplyr::near(Value, 0))), by = c("geographicAreaM49", "measuredItemSuaFbs") ][ n >= 5 ][, n := NULL ] # Keep processingShare and shareDownUp computed_shares <- list() computed_shares_send <- list() # Keep negative availability negative_availability <- list() #keep shareuPdOWN updated_shareUpDOwn<-list() fixed_proc_shares <- list() original_stock_variation <- data[ measuredElementSuaFbs == "stockChange" & timePointYears >= startYear & !is.na(Value), c( "geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "Value", "flagObservationStatus", "flagMethod" ) ] dbg_print("starting derived production loop") if (length(primaryInvolvedDescendents) == 0) { message("No primary commodity involved in this country") } else { #USED TO AVOID DUPLICATES data[, Processed_estimed := FALSE] for (lev in sort(unique(tree$processingLevel))) { #testing purpose # lev=0 dbg_print(paste("derived production loop, level", lev)) treeCurrentLevel <- tree[ !is.na(Value) & processingLevel == lev & measuredElementSuaFbs == 'extractionRate', .( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value ) ] #tree containing children of all parent of current level tree_parent_Level<- tree[ !is.na(Value) & measuredElementSuaFbs == 'extractionRate' & measuredItemParentCPC %chin% treeCurrentLevel[[p$parentVar]], .( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value, processingLevel ) ] ############# Create stocks, if missing #################### # Stocks will be generated also for those cases for which we have data condition_for_stocks <- data$stockable == TRUE & data$measuredItemSuaFbs %chin% items_to_generate_stocks & #data$measuredItemSuaFbs %chin% treeCurrentLevel$measuredItemParentCPC & data$measuredElementSuaFbs %chin% c('production', 'imports', 'exports') if (any(condition_for_stocks)) { dbg_print("generating stocks") data_histmod_stocks <- data[ measuredItemSuaFbs %chin% historical_avail_stocks$measuredItemSuaFbs ] if (nrow(data_histmod_stocks) > 0) { dbg_print("data for histmod available") data_histmod_stocks <- data_histmod_stocks[, .( supply_inc = sum( Value[measuredElementSuaFbs %chin% c("production", "imports")], - Value[measuredElementSuaFbs %chin% c("exports", "stockChange")], na.rm = TRUE ), supply_exc = sum( Value[measuredElementSuaFbs %chin% c("production", "imports")], - Value[measuredElementSuaFbs == "exports"], na.rm = TRUE ) ), keyby = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ][, trend := seq_len(.N), by = c("geographicAreaM49", "measuredItemSuaFbs") ] dbg_print("coeffs_stocks_mod") data_histmod_stocks[, c("c_int", "c_sup", "c_trend") := coeffs_stocks_mod(.SD), by = c("geographicAreaM49", "measuredItemSuaFbs") ][, supply_inc_pred := c_int + c_sup * supply_exc + c_trend * trend, ][, `:=`( min_new_supply_inc = min(supply_inc[supply_inc > 0 & timePointYears >= 2009 & timePointYears < startYear], na.rm = TRUE), avg_new_supply_inc = mean(supply_inc[supply_inc > 0 & timePointYears >= 2009 & timePointYears < startYear], na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemSuaFbs") ][ supply_inc_pred <= 0 & timePointYears >= startYear, supply_inc_pred := min_new_supply_inc ][, delta_pred := supply_exc - supply_inc_pred ] data_histmod_stocks[ supply_inc > 100, abs_stock_perc := abs(supply_exc - supply_inc) / supply_inc ] data_histmod_stocks[, abs_delta_pred_perc := abs(delta_pred) / avg_new_supply_inc ] # Max without the actual maximum, to avoid extremes data_histmod_stocks[, #upper_abs_stock_perc := max(abs_stock_perc[-(which(abs_stock_perc == max(abs_stock_perc, na.rm = TRUE)))], na.rm = TRUE), upper_abs_stock_perc := max(abs_stock_perc[timePointYears < startYear], na.rm = TRUE), by = c("geographicAreaM49", "measuredItemSuaFbs") ] # upper_abs_stock_perc can be infinite if abs_stock_perc is always missing # (note that abs_stock_perc is calculated only for supply > 100) data_histmod_stocks[ abs_delta_pred_perc > upper_abs_stock_perc & timePointYears >= startYear & !is.infinite(upper_abs_stock_perc), delta_pred := upper_abs_stock_perc * avg_new_supply_inc * sign(delta_pred) ] data_for_stocks <- data_histmod_stocks[ timePointYears >= startYear , .(geographicAreaM49, measuredItemSuaFbs, timePointYears, delta = delta_pred) ] if (nrow(data_for_stocks) > 0) { # HERE data_for_stocks <- dt_left_join( data_for_stocks, all_opening_stocks[, .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, new_opening = Value) ], by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) stockdata <- data[ Protected == TRUE & measuredElementSuaFbs == "stockChange" & !is.na(Value) & measuredItemSuaFbs %chin% data_for_stocks$measuredItemSuaFbs, .( geographicAreaM49, measuredItemSuaFbs, timePointYears, stockvar = Value ) ] data_for_stocks <- dt_left_join( data_for_stocks, stockdata, by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data_for_stocks[!is.na(stockvar), delta := stockvar] data_for_stocks[, stockvar := NULL] data_for_stocks[is.na(new_opening), new_opening:=0] # Stock withdrawal cannot exceed opening stocks in the first year data_for_stocks[ timePointYears == startYear & delta < 0 & abs(delta) > new_opening, delta := - new_opening ] # NOTE: Data here should be ordered by country/item/year (CHECK) data_for_stocks <- update_opening_stocks(data_for_stocks) data <- dt_left_join( data, data_for_stocks, by = c('geographicAreaM49', 'timePointYears', 'measuredItemSuaFbs') ) data[ measuredElementSuaFbs == "stockChange" & Protected == FALSE & !is.na(delta), `:=`( Value = delta, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] data[, c("delta", "new_opening") := NULL] all_opening_stocks <- dt_full_join( all_opening_stocks, data_for_stocks[, .( geographicAreaM49, measuredItemFbsSua = measuredItemSuaFbs, timePointYears, new_opening ) ], by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ) all_opening_stocks[ !is.na(new_opening) & (round(new_opening) != round(Value) | is.na(Value)), `:=`( Value = new_opening, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] all_opening_stocks[, new_opening := NULL] } } } ############# END / Create stocks, if missing ################## #Correcting stocks data_st<-copy(data) data_st[, supply := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], # XXX p$stockCode is "stockChange", not "stockChange" - Value[get(p$elementVar) %in% c(p$exportCode)], na.rm = TRUE ), by = c(p$geoVar, p$yearVar, p$itemVar) ] data_st<-data_st[measuredElementSuaFbs=="stockChange",] data_stocks <- merge( data_st, all_opening_stocks[,list(geographicAreaM49,measuredItemSuaFbs=measuredItemFbsSua, timePointYears,openingStocks=Value)], by = c(p$geoVar, p$itemVar, p$yearVar) ) data_stocks[,stockCheck:=ifelse(sign(Value) == 1 & Value+openingStocks>2*supply & supply>0,TRUE,FALSE)] #create max_column: data_stocks[, maxValue := 2*supply-openingStocks] data_stocks[, stocks_checkVal := ifelse(stockCheck == T & sign(maxValue)==1, maxValue , 0)] data_stocks[flagObservationStatus=="E" & flagMethod=="f",Protected:=FALSE] for(i in startYear:max(unique(as.numeric(data_stocks$timePointYears)))){ data_stocks[,Value:=ifelse(timePointYears==i & stockCheck==TRUE & Protected==FALSE,stocks_checkVal,Value)] data_stocks[order(geographicAreaM49,measuredItemSuaFbs, timePointYears),prev_stocks:=c(NA, Value[-.N]), by= c(p$geoVar, p$itemVar)] data_stocks[order(geographicAreaM49,measuredItemSuaFbs, timePointYears),prev_opening:=c(NA, openingStocks[-.N]), by= c(p$geoVar, p$itemVar)] if(i<max(unique(as.numeric(data_stocks$timePointYears)))){ data_stocks[,openingStocks:=ifelse(timePointYears==i+1 ,prev_opening+prev_stocks,openingStocks)] } } data <- merge( data, data_stocks[,list(geographicAreaM49,measuredItemSuaFbs,measuredElementSuaFbs, timePointYears,corr_stocks=Value,stockCheck)], by = c(p$geoVar,p$elementVar, p$itemVar, p$yearVar), all.x = TRUE ) data[ measuredElementSuaFbs == "stockChange" & Protected == FALSE & !is.na(corr_stocks) & stockCheck==TRUE, `:=`( Value = corr_stocks, flagObservationStatus = "E", flagMethod = "n", Protected = FALSE ) ] data[ measuredElementSuaFbs == "stockChange" & flagObservationStatus=="E" & flagMethod=="f" & !is.na(corr_stocks) & stockCheck==TRUE, `:=`( Value = corr_stocks, flagObservationStatus = "E", flagMethod = "n", Protected = FALSE ) ] data[,corr_stocks:=NULL] data[,stockCheck:=NULL] stock_correction_send<-data[measuredElementSuaFbs == "stockChange" & flagObservationStatus=="E" & flagMethod=="n",] write.csv(stock_correction_send,tmp_file_Stock_correction) all_opening_stocks <- merge( all_opening_stocks, data_stocks[,list(geographicAreaM49,measuredItemFbsSua=measuredItemSuaFbs, timePointYears,corr_op_stocks=openingStocks,stockCheck)], by = c(p$geoVar, "measuredItemFbsSua", p$yearVar), all.x = TRUE ) all_opening_stocks[, stockCheck:= dplyr::lag(stockCheck)] all_opening_stocks[ measuredElementSuaFbs == "5113" & Protected == FALSE & !is.na(corr_op_stocks) & stockCheck==TRUE, `:=`( Value = corr_op_stocks, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] all_opening_stocks[,corr_op_stocks:=NULL] all_opening_stocks[,stockCheck:=NULL] # # ############# END / Create stocks, if missing ################## message("Line 3185") dataMergeTree <- data[measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange')] setnames(dataMergeTree, "measuredItemSuaFbs", "measuredItemParentCPC") dbg_print("dataMerge + treeCurrentLevel") dataMergeTree <- merge( dataMergeTree, tree_parent_Level, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) dbg_print("dataMerge + data_tree_final") dataMergeTree <- merge( dataMergeTree, data_tree_final, by = c(p$parentVar, p$childVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) setkey(dataMergeTree, NULL) dbg_print("dataMerge availability") dataMergeTree[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], # XXX p$stockCode is "stockChange", not "stockChange" - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ] dbg_print("negative availability") negative_availability[[as.character(lev)]] <- unique( dataMergeTree[ availability < -100, .( country = geographicAreaM49, year = timePointYears, measuredItemFbsSua = measuredItemParentCPC, element = measuredElementSuaFbs, Value, flagObservationStatus, flagMethod, availability ) ] ) dbg_print("zero out negative availability") # XXX: Replace negative availability, so we get zero production, instead of negative. This, , however, should be fixed in advance, somehow. dataMergeTree[availability < 0, availability := 0] dbg_print("dataMergeTree + shareDownUp_previous") message("Line 3252") ##########Caculating and updating processed of parent-------------------------- #amsata datamergeNew <- copy(dataMergeTree) datamergeNew <- datamergeNew[, c("geographicAreaM49", "measuredItemParentCPC", "availability", "measuredItemChildCPC", "timePointYears", "extractionRate", "processingLevel", "shareDownUp"), with = FALSE ] datamergeNew <- unique(datamergeNew, by = colnames(datamergeNew)) datamergeNew <- merge( datamergeNew, data[ measuredElementSuaFbs == 'production', list(geographicAreaM49, timePointYears, measuredItemChildCPC = measuredItemSuaFbs, production = Value, Protected, Official, flagObservationStatus, flagMethod) ], by = c('geographicAreaM49', 'timePointYears', 'measuredItemChildCPC') ) setkey(datamergeNew, NULL) datamergeNew[, manual := flagObservationStatus == "E" & flagMethod == "f"] datamergeNew[, c("flagObservationStatus", "flagMethod") := NULL] datamergeNew_zw <- datamergeNew[measuredItemChildCPC %chin% zeroWeight] datamergeNew <- datamergeNew[measuredItemChildCPC %!in% zeroWeight] datamergeNew <- dt_left_join( datamergeNew, data_Pshare, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) datamergeNew <- dt_left_join( datamergeNew, data_ShareUpDoawn_final, by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ) datamergeNew <- datamergeNew[, c("geographicAreaM49", "measuredItemParentCPC", "availability", "Pshare","NewLoss","Loss", "measuredItemChildCPC", "timePointYears", "extractionRate", "processingLevel", "shareDownUp", "shareUpDown", "production", "Protected", "flagObservationStatus", "flagMethod", "Official", "manual"), with = FALSE ] datamergeNew <- unique(datamergeNew) # datamergeNew[,zeroweight:=measuredItemChildCPC %in% zeroWeight] # including processed of parent datamergeNew <- dt_left_join( datamergeNew, data[ measuredElementSuaFbs == 'foodManufacturing', list(geographicAreaM49, timePointYears, measuredItemParentCPC = measuredItemSuaFbs, processedBis = Value, processedProt = Protected) ], by = c('geographicAreaM49', 'timePointYears', 'measuredItemParentCPC') ) # datamergeNew[timePointYears >= 2014 & Protected == FALSE, Value := NA][, Protected := NULL] datamergeNew[timePointYears >= startYear & Protected == FALSE, production := NA] datamergeNew[timePointYears >= startYear & processedProt == FALSE, processedBis := NA] # Calculate the number of child with protected production for each parent datamergeNew[, Number_childPro := sum(Protected == TRUE & shareUpDown > 0, na.rm = TRUE), by = c(p$parentVar, p$geoVar, p$yearVar) ] datamergeNew[ , AllProotected:=sum(shareUpDown[Protected==TRUE],na.rm = TRUE), by=c("geographicAreaM49","timePointYears","measuredItemParentCPC") ] datamergeNew[is.na(shareUpDown),shareUpDown:=0] #Update of the share up down . Giulia: sbagliato, se viene cambiata solo una down up mi trovo con inconsistency datamergeNew[extractionRate>0 , shareUpDown:=ifelse(Protected==TRUE & AllProotected!=1,(production*shareDownUp/extractionRate)/sum(production[Protected==TRUE]*shareDownUp[Protected==TRUE]/extractionRate[Protected==TRUE],na.rm = TRUE)* (1-sum(shareUpDown[Protected==FALSE],na.rm = TRUE)),shareUpDown), by=c("geographicAreaM49","timePointYears","measuredItemParentCPC") ] datamergeNew[,AllProotected:=NULL] # calculate the number of child of each parent where processed used to be send datamergeNew[, Number_child := sum(shareUpDown > 0, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] # we estimate processed quantity for parent # based on the historique trend of processed percentage datamergeNew[, Processed := ifelse(NewLoss==TRUE,Pshare * (availability-ifelse(is.na(Loss),0,Loss)),Pshare * availability)] # However, we may have cases where some production of child commodities are official datamergeNew[sign(Processed) == -1, Processed := 0] # case1: some child production are official but not all # in this case we update the shareUpDown of the child commodities for which the production is official # if the sum of their ShareUpdown is greater than 1, we update processed using the official production of those # children and then we update the shareUpDown of different child commodities datamergeNew[, c("shareUpDown_NEW", "Processed_new") := NA_real_] # A child is converted up to process of parent if it has a protected production # with shareUpDown>0, shareDownUp>0 and extractionRate > 0. this avoid issue caused by multiple parent # children with protected production datamergeNew[, child_DownUp := Protected == TRUE & shareUpDown > 0 & extractionRate > 0 & shareDownUp > 0 ] # GianLuca suggestion---------------- datamergeNew[Number_childPro > 0, #& extractionRate > 0, #sum_shareUD_high == TRUE, Processed_new := sum( production[child_DownUp == TRUE] / extractionRate[child_DownUp == TRUE] * shareDownUp[child_DownUp == TRUE], na.rm = TRUE ) / sum(shareUpDown[child_DownUp == TRUE], na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] datamergeNew[, Processed_new := ifelse(is.na(Processed_new), mean(Processed_new, na.rm = TRUE), Processed_new), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] datamergeNew[, processed_down_up := sum(child_DownUp, na.rm = TRUE) > 0, by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] datamergeNew[is.na(Processed_new) & processed_down_up == TRUE, Processed_new := 0] datamergeNew[Processed_new == 0 & processed_down_up == FALSE, Processed_new := NA_real_] datamergeNew[ Protected == TRUE & manual == FALSE, `:=`(flagObservationStatus = "T", flagMethod = "-") ] datamergeNew[ Protected == TRUE & manual == TRUE, `:=`(flagObservationStatus = "E", flagMethod = "f") ] datamergeNew[ Protected==FALSE, `:=`(flagObservationStatus = "I", flagMethod = "c") ] datamergeNew[!is.na(shareUpDown_NEW), shareUpDown := shareUpDown_NEW] # GianLuca------------------------ #Update the processed quantities dataForProc <- datamergeNew[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability","Pshare","Processed", "processedBis", "Processed_new"), with = FALSE ] dataForProc <- unique(dataForProc) dataForProc[ timePointYears >= startYear & !is.na(Processed_new), processedBis := Processed_new ] # cancel the automatic update of Pshare for 2014 onward #However this lines can be kept for futur improvement # dataForProc[, # Pshare := processedBis / availability, # by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") # ] # dataForProc[is.nan(Pshare), Pshare := NA_real_] # dataForProc[Pshare > 1, Pshare := 1] # dataForProc[Pshare < 0, Pshare := 0] # dataForProc <- # dataForProc[ # order(geographicAreaM49, measuredItemParentCPC, timePointYears), # Pshare_avr := rollavg(Pshare, order = 3), # by = c("geographicAreaM49", "measuredItemParentCPC") # ] # # setkey(dataForProc, NULL) # # dataForProc[timePointYears > 2013 & is.na(Pshare), Pshare := Pshare_avr] # # dataForProc[, Pshare_avr := NULL] # # dataForProc[, Processed := Pshare * availability] dataForProc[!is.na(Processed_new), Processed := Processed_new] datamergeNew <- datamergeNew[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "measuredItemChildCPC", "extractionRate", "processingLevel", "shareDownUp", "shareUpDown", "production", "Protected", "flagObservationStatus", "flagMethod", "Official", "manual", "processed_down_up"), with = FALSE ] datamergeNew <- merge( dataForProc, datamergeNew, by = c(p$geoVar, p$yearVar, p$parentVar), allow.cartesian = TRUE ) setkey(datamergeNew, NULL) #if the shareUpDown of a zeroweight coproduct is updated, the shareUpDown of #the corresponding zeroweight should also be updated #merge zeroweight with the tree datamergeNew_zeroweight <- merge( datamergeNew, zw_coproduct , by = "measuredItemChildCPC", allow.cartesian = TRUE ) setkey(datamergeNew_zeroweight, NULL) datamergeNew_zeroweight[, measuredItemChildCPC := zeroweight] datamergeNew_zeroweight <- datamergeNew_zeroweight[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "measuredItemChildCPC", "Pshare", "shareUpDown", "Processed", "flagObservationStatus", "flagMethod", "processed_down_up"), with = FALSE ] #correction datamergeNew_zeroweight<- datamergeNew_zeroweight[, shareUpDown := sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") ] datamergeNew_zeroweight <- unique(datamergeNew_zeroweight) #/correction datamergeNew_zeroweight <- merge( datamergeNew_zeroweight, datamergeNew_zw, by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "measuredItemChildCPC") ) datamergeNew <- datamergeNew[, colnames(datamergeNew_zeroweight), with = FALSE] datamergeNew_final <- rbind(datamergeNew, datamergeNew_zeroweight) #some correction datamergeNew_final[is.na(shareUpDown), shareUpDown := NA_real_] updated_shareUpDOwn[[as.character(lev)]] <- datamergeNew_final[ processingLevel == lev, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "measuredItemChildCPC", "shareUpDown", "flagObservationStatus", "flagMethod"), with = FALSE ] #/processed of parent----------------- estimated_processed <- datamergeNew_final[, list(geographicAreaM49, timePointYears, measuredItemSuaFbs = measuredItemParentCPC, Processed, processed_down_up) ] estimated_processed <- unique(estimated_processed) complete_food_proc <- CJ( measuredItemSuaFbs = unique(estimated_processed$measuredItemSuaFbs), measuredElementSuaFbs = 'foodManufacturing', geographicAreaM49 = unique(estimated_processed$geographicAreaM49), timePointYears = unique(estimated_processed$timePointYears) ) # rbind with anti_join data <- rbind( data, complete_food_proc[ !data, on = c('measuredItemSuaFbs', 'measuredElementSuaFbs', 'geographicAreaM49', 'timePointYears') ], fill = TRUE ) data <- dt_left_join( data, estimated_processed[timePointYears >= startYear], by = c('geographicAreaM49', 'timePointYears', 'measuredItemSuaFbs'), allow.cartesian = TRUE ) data[is.na(Protected), Protected := FALSE] data[is.na(Official), Official := FALSE] data[is.na(Processed_estimed), Processed_estimed := FALSE] data[ measuredElementSuaFbs == "foodManufacturing" & Protected == FALSE & !is.na(Processed) & Processed_estimed == FALSE, `:=`( Value = Processed, flagObservationStatus = "E", flagMethod = ifelse(processed_down_up == TRUE, "-", "i"), Processed_estimed = TRUE ) ][, c("Processed", "processed_down_up") := NULL ] ####### estimating production of derived data_production <- datamergeNew_final[ processingLevel == lev, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "Pshare", "measuredItemChildCPC", "extractionRate", "shareDownUp", "shareUpDown", "production", "Protected"), with = FALSE ] data_production <- unique(data_production) data_production <- dt_left_join( data_production, unique( data[ measuredElementSuaFbs == "foodManufacturing" & !is.na(Value), .(geographicAreaM49, timePointYears, measuredItemParentCPC = measuredItemSuaFbs, Processed_parent = Value) ] ), by = c(p$geoVar, p$yearVar, p$parentVar) ) data_production[, #new_imputation:=Processed_parent*shareUpDown*extractionRate*shareDownUp new_imputation := Processed_parent * shareUpDown * extractionRate #shareDownUp is not part of the formula ] data_production <- data_production[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "Pshare", "measuredItemChildCPC", "production", "new_imputation", "extractionRate", "shareDownUp", "shareUpDown", "Processed_parent"), with = FALSE ] data_production <- unique(data_production, by = c(colnames(data_production))) sel_vars <- c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "Pshare", "measuredItemChildCPC", "extractionRate", "shareDownUp", "shareUpDown", "Processed_parent") computed_shares[[as.character(lev)]] <- data_production[, sel_vars, with = FALSE] # XXX: change this name computed_shares_send[[as.character(lev)]] <- data_production[, sel_vars, with = FALSE] dbg_print("sum unique of new_imputation") data_production <- data_production[, .( measuredElementSuaFbs = 'production', # NOTE: the sum(unique()) is just a temporary HACK: check how to do it properly imputed_deriv_value = sum(unique(round(new_imputation, 2)), na.rm = TRUE) ), .(geographicAreaM49, timePointYears, measuredItemSuaFbs = measuredItemChildCPC) ] data_production_complete <- CJ( measuredItemSuaFbs = unique(data_production$measuredItemSuaFbs), measuredElementSuaFbs = 'production', geographicAreaM49 = unique(data_production$geographicAreaM49), timePointYears = unique(data_production$timePointYears) ) setkey(data_production_complete, NULL) sel_vars <- c('geographicAreaM49', 'timePointYears', 'measuredItemSuaFbs', 'measuredElementSuaFbs') # rbind with anti_join data <- rbind( data, data_production_complete[!data, on = sel_vars], fill = TRUE ) data <- dt_left_join(data, data_production, by = sel_vars) dbg_print("z data for shares to send") z <- data[ measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange"), c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs", "measuredElementSuaFbs", "Value", "Protected", "imputed_deriv_value"), with = FALSE ] z[ measuredElementSuaFbs == 'production' & Protected == FALSE, Value := imputed_deriv_value ] z[, imputed_deriv_value := NULL] # XXX stocks create duplicates z <- unique(z) dbg_print("dcast z data") z <- data.table::dcast( z, geographicAreaM49 + timePointYears + measuredItemSuaFbs ~ measuredElementSuaFbs, value.var = c("Value", "Protected") ) # XXX stockChange may change below (and also production, if required) dbg_print("z data + computed_shares_send") tmp <- z[computed_shares_send[[as.character(lev)]], on = c('geographicAreaM49' = 'geographicAreaM49', 'timePointYears' = 'timePointYears', 'measuredItemSuaFbs' = 'measuredItemChildCPC')] setkey(tmp, NULL) # XXX stocks create duplicates tmp <- unique(tmp) computed_shares_send[[as.character(lev)]] <- tmp dbg_print("assign production of derived to non protected/frozen data") # Assign if non-protected only non-fozen data # (XXX: here only measuredItemSuaFbs that are child should be assigned) data[ timePointYears >= startYear & Protected == FALSE & measuredElementSuaFbs == 'production' & !is.na(imputed_deriv_value), `:=`( Value = imputed_deriv_value, flagObservationStatus = "I", flagMethod = "c") ] data[, imputed_deriv_value := NULL] } ### Processed check and remove processed that does not link to children ProcessedCheck = copy(data) setnames(ProcessedCheck, c("measuredItemSuaFbs", "Value"), c("measuredItemParentCPC", "foodManufacturing")) ProcessedCheck = ProcessedCheck[measuredElementSuaFbs == "foodManufacturing" & flagMethod == "i" , ] ProductionCheck = copy(data) setnames(ProductionCheck, c("measuredItemSuaFbs", "Value"), c("measuredItemChildCPC", "production")) ProductionCheck = ProductionCheck[measuredElementSuaFbs == "production" & flagMethod == "c" , ] CheckProcessedData = merge( ProcessedCheck[, .(geographicAreaM49, timePointYears, measuredItemParentCPC, foodManufacturing)], tree[measuredElementSuaFbs == "extractionRate", .(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears)], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears"), all.x = TRUE ) CheckProcessedData = merge( CheckProcessedData, ProductionCheck[, .(geographicAreaM49, timePointYears, measuredItemChildCPC, production)], by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears"), all.x = TRUE ) CheckProcessedData[, ProcessedCheck := sum(production, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC")] CheckProcessedData[ProcessedCheck == 0, foodManufacturing := 0 ] CheckProcessedData = subset(CheckProcessedData, ProcessedCheck == 0) if(nrow(CheckProcessedData)>0) { saveProcessedCheck = unique(CheckProcessedData[ , list(geographicAreaM49, measuredItemSuaFbs = measuredItemParentCPC, measuredElementSuaFbs = "foodManufacturing", Value_processedCheck = foodManufacturing, timePointYears)]) saveProcessedCheck = saveProcessedCheck[timePointYears %in% as.character(startYear:endYear),]} # save these back to data if(exists("saveProcessedCheck")){ data = merge(data, saveProcessedCheck, by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs", "measuredElementSuaFbs"), all.x=T) data[measuredElementSuaFbs == "foodManufacturing" & !is.na(Value_processedCheck) & Value != 0, Value := Value_processedCheck ] data[, Value_processedCheck := NULL] } } # end of derived production loop data[measuredElementSuaFbs == "production" & dplyr::near(Value,0) & flagObservationStatus == "I" & flagMethod == "c", `:=` (Value = NA, flagObservationStatus = NA, flagMethod = NA) ] setkey(data, NULL) computed_shares <- rbindlist(computed_shares) updated_shareUpDOwn <- rbindlist(updated_shareUpDOwn) updated_shareUpDOwn<- updated_shareUpDOwn[timePointYears %in% startYear:endYear] shareUpDown_to_save <- copy(updated_shareUpDOwn) shareUpDown_to_save[, measuredElementSuaFbs := "5431"] setnames( shareUpDown_to_save, c("measuredItemParentCPC", "measuredItemChildCPC", "shareUpDown"), c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree", "Value") ) # shareUpDown_to_save <- shareUpDown_to_save[!is.na(Value)] shareUpDown_to_save[is.na(Value),Value:=0] data_shareUpDown_sws <- GetData(sessionKey_shareUpDown) setcolorder( shareUpDown_to_save, names(data_shareUpDown_sws)) #shareUpDown_to_save[, Value := round(Value, 3)] faosws::SaveData( domain = "suafbs", dataset = "up_down_share", data = shareUpDown_to_save, waitTimeout = 20000 ) remove_connection<-data_shareUpDown_sws[((measuredItemParentCPC_tree == "02211" & measuredItemChildCPC_tree == "22212") | #cheese from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC_tree == "22110.02" & measuredItemChildCPC_tree == "22251.01") | (measuredItemParentCPC_tree == "02211" & measuredItemChildCPC_tree == "22251.02"))] if (nrow(remove_connection)>0){ remove_connection[,`:=`(Value = NA, flagObservationStatus = NA, flagMethod = NA)] faosws::SaveData( domain = "suafbs", dataset = "up_down_share", data = remove_connection, waitTimeout = 20000 ) } dbg_print("end of derived production loop") data_deriv <- data[ measuredElementSuaFbs == 'production' & timePointYears %in% yearVals, list( geographicAreaM49, measuredElementSuaFbs = "5510", measuredItemFbsSua = measuredItemSuaFbs, timePointYears, Value, flagObservationStatus, flagMethod ) ] # save processed data data_processed <- data[ measuredElementSuaFbs == 'foodManufacturing' & timePointYears %in% yearVals, list( geographicAreaM49, measuredElementSuaFbs = "5023", measuredItemFbsSua = measuredItemSuaFbs, timePointYears, Value, flagObservationStatus, flagMethod ) ] # Save stock data in SUA Unbalanced data_stock_to_save <- data[ measuredElementSuaFbs == 'stockChange' & timePointYears %in% yearVals & !is.na(Value), list( geographicAreaM49, measuredElementSuaFbs = "5071", measuredItemFbsSua = measuredItemSuaFbs, timePointYears, Value, flagObservationStatus, flagMethod ) ] opening_stocks_to_save <- copy(all_opening_stocks) opening_stocks_to_save[, Protected := NULL] data_to_save_unbalanced <- rbind( data_deriv, data_processed, data_stock_to_save, opening_stocks_to_save ) data_to_save_unbalanced <- data_to_save_unbalanced[!is.na(Value)] dbg_print("complete data elements") data <- plyr::ddply( data, .variables = c('geographicAreaM49', 'timePointYears'), .fun = function(x) addMissingElements(as.data.table(x), p) ) setDT(data) ######################## OUTLIERS ################################# # re-writing of Cristina's outliers plugin with data.table syntax # # Download also calories elemKeys_all <- c(elemKeys, "664") # Get ALL data from SUA BALANCED, do an anti-join, set to NA whatever was not # generated here so to clean the session on unbalanced of non-existing cells if (CheckDebug()) { key_all <- DatasetKey( domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys_all), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), # Get from 2010, just for the SUA aggregation timePointYears = Dimension(name = "timePointYears", keys = as.character(2010:endYear)) ) ) } else { key_all <- swsContext.datasets[[1]] key_all@dimensions$timePointYears@keys <- as.character(2010:endYear) key_all@dimensions$measuredItemFbsSua@keys <- itemKeys key_all@dimensions$measuredElementSuaFbs@keys <- elemKeys_all key_all@dimensions$geographicAreaM49@keys <- COUNTRY } data_suabal <- GetData(key_all) dbg_print("start outliers") if (FIX_OUTLIERS == TRUE) { sel_vars <- c('geographicAreaM49', 'timePointYears', 'measuredItemSuaFbs', 'measuredElementSuaFbs') commDef <- ReadDatatable("fbs_commodity_definitions") # XXX: updated? stopifnot(nrow(commDef) > 0) primaryProxyPrimary_items <- commDef[proxy_primary == "X" | primary_commodity == "X"]$cpc food_items <- commDef[food_item == "X"]$cpc fbsTree <- ReadDatatable("fbs_tree") dairy_meat_items <- fbsTree[id3 %chin% c("2948", "2943"), item_sua_fbs] dout <- CJ( geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears), measuredItemSuaFbs = unique(data$measuredItemSuaFbs), measuredElementSuaFbs = unique(data$measuredElementSuaFbs) ) dout <- data[dout, on = sel_vars] # dout <- merge(dout, codes, by.x = "measuredElementSuaFbs",by.y = "name",all.x = TRUE) # dout[, measuredElementSuaFbs := name] # dout[, measuredElementSuaFbs := NULL] dout[is.na(Protected), Protected := FALSE] data_suabalout <-data_suabal refYear=(startYear-3):(startYear-1) suabalCJ <- CJ( geographicAreaM49 = unique(data_suabalout$geographicAreaM49), timePointYears = unique(as.character(refYear)), measuredItemFbsSua = unique(data_suabalout$measuredItemFbsSua), measuredElementSuaFbs = unique(data_suabalout$measuredElementSuaFbs) ) outlier_suabal = merge(suabalCJ, data_suabalout, all.x=T, by = c("geographicAreaM49", "timePointYears", "measuredItemFbsSua", "measuredElementSuaFbs")) # merge in names (will also keep only elemnts for which we need thresholds, i.e. excl. stock opeings) setnames(outlier_suabal, "measuredItemFbsSua", "measuredItemSuaFbs") outlier_suabal[, `:=`( production = Value[measuredElementSuaFbs == "5510"], supply = sum(Value[measuredElementSuaFbs %in% c("5510", "5610")], - Value[measuredElementSuaFbs %in% c("5910", "5071")], na.rm = TRUE), domsupply = sum(Value[measuredElementSuaFbs %in% c("5510", "5610")], na.rm = TRUE) ), by = c('geographicAreaM49', 'measuredItemSuaFbs', 'timePointYears') ] outlier_suabal[measuredElementSuaFbs %chin% c("5520", "5165", "5164"), element_supply := supply] outlier_suabal[measuredElementSuaFbs == "5525", element_supply := production] outlier_suabal[measuredElementSuaFbs == "5016", element_supply := domsupply] outlier_suabal[element_supply < 0, element_supply := NA_real_] outlier_suabal[, ratio := Value / element_supply] # Calculate thresholds form sua balanced values outlier_suabal[, `:=`( mean_ratio = mean(ratio[timePointYears %in% refYear], na.rm = TRUE), Meanold = mean(Value[timePointYears %in% refYear], na.rm = TRUE) ), by = c('geographicAreaM49', 'measuredItemSuaFbs', 'measuredElementSuaFbs') ] outlier_suabal[mean_ratio > 1, mean_ratio := 1] outlier_suabal[mean_ratio < 0, mean_ratio := 0] outlier_suabal[is.na(mean_ratio) | is.nan(mean_ratio), mean_ratio := 0] outlier_suabal[is.na(Meanold) | is.nan(Meanold), Meanold := 0] outlier_suabal[, abs_diff_threshold := ifelse(measuredElementSuaFbs == "5520", 0.1, 0.05)] outlier_suabal <- merge(outlier_suabal,codes,by = "measuredElementSuaFbs",all.x = TRUE) outlier_suabal <- outlier_suabal[!is.na(name)] outlier_suabal[,measuredElementSuaFbs := NULL] setnames(outlier_suabal, "name","measuredElementSuaFbs") # Protecting here Ee as we should not correct already corrected outliers (commented because otherwise if you change production the outlier is not corrected accordingly) # dout[flagObservationStatus == "E" & flagMethod == "e", Protected := TRUE] dout[, `:=`( production = Value[measuredElementSuaFbs == "production"], supply = sum(Value[measuredElementSuaFbs %in% c("production", "imports")], - Value[measuredElementSuaFbs %in% c("exports", "stockChange")], na.rm = TRUE), domsupply = sum(Value[measuredElementSuaFbs %in% c("production", "imports")], na.rm = TRUE) ), by = c('geographicAreaM49', 'measuredItemSuaFbs', 'timePointYears') ] dout[measuredElementSuaFbs %chin% c("feed", "industrial", "tourist"), element_supply := supply] dout[measuredElementSuaFbs == "seed", element_supply := production] dout[measuredElementSuaFbs == "loss", element_supply := domsupply] dout[element_supply < 0, element_supply := NA_real_] dout[, ratio := Value / element_supply] dout[ratio<0 , ratio:=0] dout = merge(dout, unique(outlier_suabal[, .(measuredElementSuaFbs, geographicAreaM49, measuredItemSuaFbs, mean_ratio, Meanold, abs_diff_threshold)]), by = c("measuredElementSuaFbs", "geographicAreaM49", "measuredItemSuaFbs"), all.x=T) # New series not deleted even if hisotircal mean is zero, only new series for meat and dairy product losses are removed dout[Meanold == 0 & mean_ratio == 0 & measuredElementSuaFbs %in% "loss" & measuredItemSuaFbs %in% dairy_meat_items ,`:=` (impute = 0, Protected = TRUE)] dout[Meanold == 0 & mean_ratio == 0 & measuredElementSuaFbs %in% c("feed", "seed", "loss", "industrial", "tourist" ) & Value == 0, impute := NA_real_] # # If the element is new, there will be no `mean_ratio` and `Meanold`, thus we # use the new values to re-calculate them. dout[ timePointYears >= startYear & (is.na(mean_ratio) | is.nan(mean_ratio) | is.infinite(mean_ratio) | mean_ratio == 0), mean_ratio := median(ratio[timePointYears >= startYear], na.rm = TRUE), by = c('geographicAreaM49', 'measuredItemSuaFbs', 'measuredElementSuaFbs') ] dout[ timePointYears >= startYear & (is.na(Meanold) | is.nan(Meanold) | is.infinite(Meanold) | Meanold == 0), Meanold := median(Value[timePointYears >= startYear], na.rm = TRUE), by = c('geographicAreaM49', 'measuredItemSuaFbs', 'measuredElementSuaFbs') ] dout[mean_ratio > 1, mean_ratio := 1] dout[, abs_diff_threshold := ifelse(measuredElementSuaFbs == "feed", 0.1, 0.05)] dout[ Protected == FALSE & timePointYears %in% yearVals & mean_ratio > 0 & abs(element_supply) > 0 & measuredElementSuaFbs %chin% c("feed", "seed", "loss", "industrial", "tourist") & # the conditions below define the outlier, or cases that were NA (is.na(Value) | abs(ratio - mean_ratio) > abs_diff_threshold | mean_ratio == 1 | (mean_ratio != 0 & dplyr::near(ratio, 0)) | (outside(Value / Meanold, 0.5, 2) & outside(Value - Meanold, -10000, 10000))), impute := element_supply*mean_ratio ] # get rid of utilizations that are zero in 2014-2019 # dout[Meanold == 0 & mean_ratio == 0 & measuredElementSuaFbs %in% c("feed", "seed", "loss", "industrial" ), impute := 0 ] # Remove imputation for loss that is non-food and non-primaryProxyPrimary dout[ (!is.na(Value)| !is.na(impute)) & measuredElementSuaFbs == "loss" & !(measuredItemSuaFbs %chin% food_items & measuredItemSuaFbs %chin% primaryProxyPrimary_items), impute := 0 ] fbsTree <- ReadDatatable("fbs_tree") # Remove imputation for seed of Fruits and vegetables dout[ (!is.na(Value)| !is.na(impute)) & measuredElementSuaFbs == "seed" & measuredItemSuaFbs %chin% fbsTree[id3 == "2918"|id3=="2919"]$item_sua_fbs, impute := 0 ] # Exclude feed as the first time it needs to be generated, without saving # outliers to sua_unbalanced as they have E,e flag (which is protected...). # In other words, feed has not been run yet if first time. if (STOP_AFTER_DERIVED == TRUE) { dout <- dout[measuredElementSuaFbs != "feed"] } dout <- dout[ !is.na(impute) & (is.na(Value) | round(Value, 1) != round(impute, 1)), list( geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears, Value_imputed = impute ) ] dout <- dout[timePointYears %in% yearVals] if (nrow(dout) > 0) { data <- dt_full_join(data, dout, by = sel_vars) data[ !is.na(Value_imputed), `:=`( Value = Value_imputed, flagObservationStatus = "E", flagMethod = "e", Protected = FALSE) ] data_outliers <- data[!is.na(Value_imputed) & measuredElementSuaFbs %in% c("feed", "seed", "loss", "industrial", "tourist")] data_outliers[,Value := ifelse(Value ==0, NA_real_,Value)] data_outliers[, flagObservationStatus := ifelse(is.na(Value) , NA_character_,flagObservationStatus)] data_outliers[, flagMethod := ifelse(Value == is.na(Value) , NA_character_,flagMethod)] data[, Value_imputed := NULL] } } dbg_print("end outliers") ####################### / OUTLIERS ################################# ##################### INDUSTRIAL-TOURISM ############################### dbg_print("Fix tourism/industrial") # data[, Protected_orig := Protected] # data[flagObservationStatus == "E" & flagMethod == "e", Protected := TRUE] # In the past, industrial contained what is now tourism => # remove tourism from industrial. # XXX: it seems (actually, is) slow. if (COUNTRY %in% NonSmallIslands) { ind_tour_tab <- data[ measuredItemSuaFbs %chin% Utilization_Table[food_item == "X"]$cpc_code & timePointYears >= startYear & measuredElementSuaFbs %chin% c("industrial", "tourist") & !is.na(Value), .SD[.N == 2], # both industrial and tourism need to be non-missing by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ] ind_tour_tab[, any_protected := any(Protected == TRUE), by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ] ind_tour_tab <- ind_tour_tab[any_protected == FALSE] ind_tour_tab[, any_protected := FALSE] ind_tour_tab <- ind_tour_tab[, .( indNoTour = ifelse(sign(Value[measuredElementSuaFbs == "tourist"])==1,Value[measuredElementSuaFbs == "industrial"] - Value[measuredElementSuaFbs == "tourist"],Value[measuredElementSuaFbs == "industrial"]) ), by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ] ind_tour_tab[indNoTour < 0, indNoTour := 0] data <- dt_left_join( data, ind_tour_tab, by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data[ measuredElementSuaFbs == "industrial" & !is.na(indNoTour) & Protected == FALSE, `:=`( Value = indNoTour, # XXX: probably other flags (initially protected, then unprotected) flagObservationStatus = "E", flagMethod = "e" ) ] data[, indNoTour := NULL] } # data[, Protected := Protected_orig] # data[, Protected_orig := NULL] ##################### / INDUSTRIAL-TOURISM ############################### data_ind_tour <- data[measuredElementSuaFbs %chin% c("industrial", "tourist")] if (nrow(data_ind_tour) > 0) { setnames(data_ind_tour, "measuredItemSuaFbs", "measuredItemFbsSua") data_ind_tour <- data_ind_tour[!is.na(Value), names(data_to_save_unbalanced), with = FALSE] data_ind_tour[ measuredElementSuaFbs == "industrial", measuredElementSuaFbs := "5165" ] data_ind_tour[ measuredElementSuaFbs == "tourist", measuredElementSuaFbs := "5164" ] data_to_save_unbalanced <- rbind(data_to_save_unbalanced, data_ind_tour) } if (exists("data_outliers")) { setnames(data_outliers, c("measuredItemSuaFbs", "measuredElementSuaFbs"), c("measuredItemFbsSua", "name")) data_outliers <- dt_left_join(data_outliers, codes, by = "name") data_outliers <- data_outliers[, names(data_to_save_unbalanced), with = FALSE] data_to_save_unbalanced <- rbind(data_to_save_unbalanced, data_outliers) } data_to_save_unbalanced <- data_to_save_unbalanced[timePointYears >= startYear] out <- SaveData( domain = "suafbs", dataset = "sua_unbalanced", data = data_to_save_unbalanced, waitTimeout = 20000 ) if (STOP_AFTER_DERIVED == TRUE) { dbg_print("stop after production of derived") if (exists("out")) { print(paste(out$inserted + out$ignored, "derived products written")) if (!CheckDebug()) { send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Production of derived items created", body = paste("The plugin stopped after production of derived items. A file with shareDownUp is available in", sub("/work/SWS_R_Share/", "", shareDownUp_file)) ) } } else { print("The SUA_bal_compilation plugin had a problem when saving derived data.") } stop("Plugin stopped after derived, as requested. This is fine.") } ## CLEAN sua_balanced message("wipe sua_balanced session") sessionKey_suabal = swsContext.datasets[[1]] CONFIG <- GetDatasetConfig(sessionKey_suabal@domain, sessionKey_suabal@dataset) datatoClean=GetData(sessionKey_suabal) datatoClean=datatoClean[timePointYears%in%yearVals] datatoClean[, Value := NA_real_] datatoClean[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) computed_shares_send <- rbindlist(computed_shares_send, fill = TRUE) # XXX computed_shares_send <- unique(computed_shares_send) colnames(computed_shares_send) <- sub("Value_", "", colnames(computed_shares_send)) setnames( computed_shares_send, c("timePointYears", "measuredItemSuaFbs", "measuredItemParentCPC"), c("year", "measuredItemChildCPC_tree", "measuredItemParentCPC_tree") ) computed_shares_send <- nameData( "suafbs", "ess_fbs_commodity_tree2", computed_shares_send ) setnames( computed_shares_send, c("geographicAreaM49", "geographicAreaM49_description", "measuredItemChildCPC_tree", "measuredItemChildCPC_tree_description", "measuredItemParentCPC_tree", "measuredItemParentCPC_tree_description"), c("Country", "Country_name", "Child", "Child_name", "Parent", "Parent_name") ) computed_shares_send[, zero_weigth := Child %chin% zeroWeight] computed_shares_send[, `:=`(Child = paste0("'", Child), Parent = paste0("'", Parent))] negative_availability <- rbindlist(negative_availability) if (nrow(negative_availability) > 0) { # FIXME: stocks may be generated twice for parents in multiple level, # (though, the resulting figures are the same). Fix in the prod deriv loop. negative_availability <- unique(negative_availability) negative_availability_var <- negative_availability[, .( country, year, measuredItemFbsSua, element = "availability", Value = availability, flagObservationStatus = "I", flagMethod = "i" ) ] negative_availability[, availability := NULL] negative_availability <- rbind( negative_availability, unique(negative_availability_var) #FIXME ) negative_availability <- data.table::dcast( negative_availability, country + measuredItemFbsSua + year ~ element, value.var = "Value" ) negative_availability <- nameData("suafbs", "sua_unbalanced", negative_availability) negative_availability[, measuredItemFbsSua := paste0("'", measuredItemFbsSua)] } message("Line 4233") fbsTree <- ReadDatatable("fbs_tree") ######################## rm new loss in dairy/meat ################# # dairy_meat_items <- fbsTree[id3 %chin% c("2948", "2943"), item_sua_fbs] # # # TODO: Some of the code below is repeated. It should be rewritten so # # that there is a single computation of new elements. # # data_complete_loss <- # data.table( # geographicAreaM49 = unique(data$geographicAreaM49), # timePointYears = sort(unique(data$timePointYears)))[ # unique( # data[ # measuredElementSuaFbs == "loss" & !is.na(Value), # c("geographicAreaM49", "measuredItemSuaFbs"), # with = FALSE # ] # ), # on = "geographicAreaM49", # allow.cartesian = TRUE # ] # # data_complete_loss <- # dt_left_join( # data_complete_loss, # data[ # measuredElementSuaFbs == "loss" & Value > 0, # c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "Value"), # with = FALSE # ], # by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") # ) # # data_complete_loss[, y := 1] # # # data_complete_loss <- # data_complete_loss[, # .( # t_pre = sum(y[timePointYears < startYear]), # t_post = sum(y[timePointYears >= startYear]), # na_pre = sum(is.na(Value[timePointYears < startYear])), # na_post = sum(is.na(Value[timePointYears >= startYear])) # ), # by = c("geographicAreaM49", "measuredItemSuaFbs") # ] # # # new_elements_loss <- # data_complete_loss[ # na_pre == t_pre & na_post < t_post # ][ # order(geographicAreaM49, measuredItemSuaFbs), # c("geographicAreaM49", "measuredItemSuaFbs"), # with = FALSE # ] # # new_loss_dairy_meat <- # new_elements_loss[measuredItemSuaFbs %chin% dairy_meat_items] # # new_loss_dairy_meat[, new_loss_dm := TRUE] # # data <- # new_loss_dairy_meat[data, on = c("geographicAreaM49", "measuredItemSuaFbs")] # # data[ # new_loss_dm == TRUE & # timePointYears >= startYear & # measuredElementSuaFbs == "loss" & # Protected == FALSE, # `:=`( # Value = NA_real_, # flagObservationStatus = NA_character_, # flagMethod = NA_character_ # ) # ] # # data[, new_loss_dm := NULL] ######################## END / rm new loss in dairy/meat ################# # Protect all loss data, to keep it consistent with SDG indicator, # whatever the flag is. data[measuredElementSuaFbs == "loss", Protected := TRUE] data <- dt_left_join(data, itemMap, by = "measuredItemSuaFbs") ## Split data based on the two factors we need to loop over uniqueLevels <- unique(data[, c("geographicAreaM49", "timePointYears"), with = FALSE]) uniqueLevels <- uniqueLevels[order(geographicAreaM49, timePointYears)] data[, stockable := measuredItemSuaFbs %chin% stockable_items] ## Remove stocks for non stockable items #data <- data[!(measuredElementSuaFbs == 'stockChange' & # stockable == FALSE & # flagObservationStatus != "E" & # flagMethod != "f")] data <- data[measuredElementSuaFbs != 'residual'] # Tourism consumption will be in the data only for selected countries # and needs to be protected data[measuredElementSuaFbs == "tourist", Protected := TRUE] ######################### Save UNB for validation ####################### sua_unbalanced <- data[, c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs", "measuredElementSuaFbs", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] sua_unbalanced_aux <- sua_unbalanced[, .( supply = sum(Value[measuredElementSuaFbs %chin% c("production", "imports")], - Value[measuredElementSuaFbs %chin% c("exports", "stockChange")], na.rm = TRUE), utilizations = sum(Value[!(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange"))], na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ][, imbalance := supply - utilizations ][ supply > 0, imbalance_pct := imbalance / supply * 100 ] sua_unbalanced_aux <- melt( sua_unbalanced_aux, c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs"), variable.name = "measuredElementSuaFbs", value.name = "Value" ) sua_unbalanced_aux[, `:=`(flagObservationStatus = "I", flagMethod = "i")] sua_unbalanced <- rbind(sua_unbalanced, sua_unbalanced_aux) # saveRDS( # sua_unbalanced, # file.path(R_SWS_SHARE_PATH, "FBSvalidation", COUNTRY, "sua_unbalanced.rds") # ) ######################### Save UNB for validation ####################### data[ measuredElementSuaFbs %chin% c("feed", "food", "industrial", "loss", "seed", "tourist"), movsum_value := RcppRoll::roll_sum(shift(Value), 3, fill = 'extend', align = 'right'), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ] data[ measuredElementSuaFbs %chin% c("feed", "food", "industrial", "loss", "seed", "tourist"), mov_share := movsum_value / sum(movsum_value, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # Impute share if missing data[ measuredElementSuaFbs %chin% c("feed", "food", "industrial", "loss", "seed", "tourist"), mov_share := rollavg(mov_share), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ] # Set sum of shares = 1 data[ measuredElementSuaFbs %chin% c("feed", "food", "industrial", "loss", "seed", "tourist"), mov_share := mov_share / sum(mov_share, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] data[is.na(Official), Official := FALSE] data[is.na(Protected), Protected := FALSE] # Filter elements that appear for the first time sel_vars <- c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") data_complete <- data.table( geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = sort(unique(data$timePointYears)) )[ unique(data[, sel_vars, with = FALSE]), on = "geographicAreaM49", allow.cartesian = TRUE ] sel_vars <- c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs", "timePointYears") data_complete <- dt_left_join( data_complete, data[Value > 0, c(sel_vars, "Value"), with = FALSE], by = sel_vars ) data_complete[, y := 1] data_complete <- data_complete[, .( t_pre = sum(y[timePointYears < startYear]), t_post = sum(y[timePointYears >= startYear]), na_pre = sum(is.na(Value[timePointYears < startYear])), na_post = sum(is.na(Value[timePointYears >= startYear])) ), by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs") ] new_elements <- data_complete[ na_pre == t_pre & na_post < t_post ][ order(geographicAreaM49, measuredElementSuaFbs, measuredItemSuaFbs), .(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua = measuredItemSuaFbs) ] new_loss <- new_elements[ measuredElementSuaFbs == "loss", .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, new_loss = TRUE) ] new_elements <- nameData("suafbs", "sua_unbalanced", new_elements, except = "measuredElementSuaFbs") new_elements[, measuredItemFbsSua := paste0("'", measuredItemFbsSua)] tmp_file_new <- file.path(TMP_DIR, paste0("NEW_ELEMENTS_", COUNTRY, ".csv")) write.csv(new_elements, tmp_file_new) # / Filter elements that appear for the first time dbg_print("set thresholds") if (THRESHOLD_METHOD == 'share') { dbg_print("thresholds, share") # We base thresholds on SUA balanced data suabalMinMax = copy(data_suabal) suabalMinMax <- merge(suabalMinMax, codes, by = "measuredElementSuaFbs") suabalMinMax[, measuredElementSuaFbs := name] suabalMinMax[, name := NULL] setnames(suabalMinMax, "measuredItemFbsSua", "measuredItemSuaFbs") suabalMinMax[, supply := sum( Value[measuredElementSuaFbs %in% c('production', 'imports')], - Value[measuredElementSuaFbs %in% c('exports', 'stockChange')], na.rm = TRUE ), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # NOTE: here we redefine what "supply" is just for seed. suabalMinMax[, supply := ifelse(measuredElementSuaFbs == "seed", Value[measuredElementSuaFbs == "production"], supply), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] suabalMinMax[supply < 0, supply := 0] suabalMinMax[ !(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange")), util_share := Value / supply ] suabalMinMax[is.infinite(util_share) | is.nan(util_share), util_share := NA_real_] # share < 0 shouldn't happen. Also, tourist can be negative. suabalMinMax[util_share < 0 & measuredElementSuaFbs != "tourist", util_share := 0] suabalMinMax[util_share > 1, util_share := 1] suabalMinMax[, `:=`( min_util_share = min(util_share[timePointYears %in% refYear], na.rm = TRUE), max_util_share = max(util_share[timePointYears %in% refYear], na.rm = TRUE) ), by = c("measuredItemSuaFbs", "measuredElementSuaFbs", "geographicAreaM49") ] suabalMinMax[is.infinite(min_util_share) | is.nan(min_util_share), min_util_share := NA_real_] suabalMinMax[is.infinite(max_util_share) | is.nan(max_util_share), max_util_share := NA_real_] suabalMinMax[max_util_share > 1, max_util_share := 1] data = merge(data, unique(suabalMinMax[,.(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, min_util_share, max_util_share)]), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs"), all.x = T) data[, supply := sum( Value[measuredElementSuaFbs %in% c('production', 'imports')], - Value[measuredElementSuaFbs %in% c('exports', 'stockChange')], na.rm = TRUE ), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] # NOTE: here we redefine what "supply" is just for seed. data[, supply := ifelse(measuredElementSuaFbs == "seed", Value[measuredElementSuaFbs == "production"], supply), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] data[supply < 0, supply := 0] # data[ # !(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange")), # util_share := Value / supply # ] # # data[is.infinite(util_share) | is.nan(util_share), util_share := NA_real_] # # # share < 0 shouldn't happen. Also, tourist can be negative. # data[util_share < 0 & measuredElementSuaFbs != "tourist", util_share := 0] # # data[util_share > 1, util_share := 1] # data[, # `:=`( # min_util_share = min(util_share[timePointYears %in% 2000:(startYear-1)], na.rm = TRUE), # max_util_share = max(util_share[timePointYears %in% 2000:(startYear-1)], na.rm = TRUE) # ), # by = c("measuredItemSuaFbs", "measuredElementSuaFbs", "geographicAreaM49") # ] #data[is.infinite(min_util_share) | is.nan(min_util_share), min_util_share := NA_real_] #data[is.infinite(max_util_share) | is.nan(max_util_share), max_util_share := NA_real_] #data[max_util_share > 1, max_util_share := 1] data[, `:=`( min_threshold = supply * min_util_share, max_threshold = supply * max_util_share ) ] data[, supply := NULL] } else { stop("Invalid method.") } data[, `:=`( min_adj = min_threshold / Value, max_adj = max_threshold / Value ) ] data[min_adj > 1, min_adj := 0.9] data[min_adj < 0, min_adj := 0.01] data[max_adj < 1, max_adj := 1.1] data[max_adj > 10, max_adj := 10] # XXX Too much? # Fix for new "loss" element. If loss gets in as a new utilization, # remove the thresholds for food. data <- dt_left_join( data, new_loss, by = c('geographicAreaM49', 'measuredItemSuaFbs') ) data[ new_loss == TRUE & measuredElementSuaFbs == "food", `:=`(min_adj = 0, max_adj = 10) ] # XXX is 10 enough? data[, new_loss := NULL] # / Fix for new "loss" element. If loss gets in as a new utilization, # / remove the thresholds for food. # Recalculate the levels, given the recalculation of adj factors data[, min_threshold := Value * min_adj] data[, max_threshold := Value * max_adj] # We need the min and max to be "near" one (but not too near) in case of # protected figures, so that they are not changed data[Protected == TRUE, min_adj := 0.999] data[Protected == TRUE, max_adj := 1.001] # This fix should also be done in optim function? data[ dplyr::near(min_adj, 1) & dplyr::near(max_adj, 1), `:=`( min_adj = 0.999, max_adj = 1.001 ) ] data[, `:=`( Food_Median = median(Value[measuredElementSuaFbs == "food" & timePointYears %in% (startYear-4):(startYear-1)], na.rm=TRUE), Feed_Median = median(Value[measuredElementSuaFbs == "feed" & timePointYears %in% (startYear-4):(startYear-1)], na.rm=TRUE), Industrial_Median = median(Value[measuredElementSuaFbs == "industrial" & timePointYears %in% (startYear-4):(startYear-1)], na.rm=TRUE), Production_Median = median(Value[measuredElementSuaFbs == "production" & timePointYears %in% (startYear-4):(startYear-1)], na.rm=TRUE), Import_Median = median(Value[measuredElementSuaFbs == "imports" & timePointYears %in% (startYear-4):(startYear-1)], na.rm=TRUE) ), by = c("geographicAreaM49", "measuredItemSuaFbs") ] message("Line 4630") z_comp_shares <- copy(computed_shares_send) z_comp_shares[, Protected_exports := NULL] z_comp_shares[, Protected_imports := NULL] z_comp_shares[, Protected_production := NULL] z_comp_shares[, Protected_stockChange := NULL] # FIXME: fix above z_comp_shares[, Parent := sub("'", "", Parent)] z_comp_shares[, Child := sub("'", "", Child)] setcolorder( z_comp_shares, c("Country", "Country_name", "Parent", "Parent_name", "Child", "Child_name", "year", "production", "imports", "exports", "stockChange", "extractionRate", "shareDownUp", "shareUpDown", "availability", "Pshare", "zero_weigth", "Processed_parent") ) dbg_print("SHARES workbook, create") wb <- createWorkbook() addWorksheet(wb, "SHARES") style_protected <- createStyle(fgFill = "pink") style_formula <- createStyle(fgFill = "green") style_text <- createStyle(numFmt = "TEXT") style_comma <- createStyle(numFmt = "COMMA") writeData(wb, "SHARES", z_comp_shares) for (i in c("exports", "imports", "production", "stockChange")) { a_col <- grep(paste0("^", i, "$"), names(z_comp_shares)) a_rows <- which(computed_shares_send[[paste0("Protected_", i)]] == TRUE) + 1 if (all(length(a_col) > 0, length(a_rows) > 0)) { addStyle(wb, sheet = "SHARES", style_protected, rows = a_rows, cols = a_col) } } addStyle(wb, sheet = "SHARES", style_text, rows = 1:nrow(z_comp_shares) + 1, cols = grep("^(Parent|Child)$", names(z_comp_shares)), gridExpand = TRUE, stack = TRUE) addFilter(wb, "SHARES", row = 1, cols = 1:ncol(z_comp_shares)) # Formulas pos <- lapply(colnames(z_comp_shares), function(x) letters[which(colnames(z_comp_shares) == x)]) names(pos) <- colnames(z_comp_shares) sheet_rows <- 1 + seq_len(nrow(z_comp_shares)) frml_start <- which(colnames(z_comp_shares) == "Processed_parent") + 2 z_comp_shares[, frml_prot_no_zw := computed_shares_send$Protected_production == TRUE & zero_weigth == FALSE] z_comp_shares[, frml_prot_no_zw_zero_updown := computed_shares_send$Protected_production == TRUE & zero_weigth == FALSE & dplyr::near(shareUpDown, 0)] z_comp_shares[, prot := computed_shares_send$Protected_production] z_comp_shares[, frml_n_prot_zero_updown := sum(prot == TRUE & dplyr::near(shareUpDown, 0) == TRUE), by = c("Parent", "year")] z_comp_shares[, frml_n_prot := sum(prot == TRUE), by = c("Parent", "year")] z_comp_shares[, prot := NULL] z_comp_shares[, frml_multi_parent := length(unique(Parent)) > 1, by = c("Child", "year")] z_comp_shares[, frml_any_prot_zero_updown := any(frml_prot_no_zw_zero_updown == TRUE), by = c("Parent", "year")] z_comp_shares[, frml_process_parent_num := paste0(pos$production, sheet_rows, "*", pos$shareDownUp, sheet_rows, "/", pos$extractionRate, sheet_rows)] z_comp_shares[, frml_process_parent_den := paste0(pos$shareUpDown, sheet_rows)] z_comp_shares[, frml_any_prot := any(frml_prot_no_zw == TRUE), by = c("Parent", "year")] z_comp_shares[, frml_process_parent := paste0(pos$availability, sheet_rows, "*", pos$Pshare, sheet_rows)] z_comp_shares[, frml_process_parent := dplyr::case_when( frml_any_prot_zero_updown == TRUE & !is.na(frml_n_prot) & !is.na(frml_n_prot_zero_updown) & frml_n_prot == frml_n_prot_zero_updown ~ frml_process_parent, frml_any_prot == TRUE ~ paste("(", paste(frml_process_parent_num[frml_prot_no_zw == TRUE], collapse = " + "), ") / (", paste(frml_process_parent_den[frml_prot_no_zw == TRUE], collapse = " + "), ")"), TRUE ~ frml_process_parent ), by = c("Parent", "year") ] #z_comp_shares[, frml_process_parent := paste0(pos$availability, sheet_rows, "*", pos$Pshare, sheet_rows)] #z_comp_shares[frml_any_prot == TRUE, frml_process_parent := paste("(", paste(frml_process_parent_num[frml_prot_no_zw == TRUE], collapse = " + "), ") / (", paste(frml_process_parent_den[frml_prot_no_zw == TRUE], collapse = " + "), ")"), by = c("Parent", "year")] ## XXX Here we should actually check that is protected AND zero Updown just for ONE #z_comp_shares[frml_any_prot_zero_updown == TRUE, frml_process_parent := paste(frml_process_parent[frml_prot_no_zw == TRUE], collapse = " + "), by = c("Parent", "year")] z_comp_shares[, frml_prod := paste0(letters[frml_start], sheet_rows, "*", pos$extractionRate, sheet_rows, "*", pos$shareUpDown, sheet_rows)] z_comp_shares[frml_multi_parent == TRUE, frml_prod := paste(frml_prod, collapse = " + "), by = c("Child", "year")] z_comp_shares[, frml_updown := paste0(pos$shareUpDown, sheet_rows)] z_comp_shares[, frml_check_updown := paste(frml_updown[zero_weigth == FALSE], collapse = " + "), by = c("Parent", "year")] z_comp_shares[, frml_downup := paste0(pos$shareDownUp, sheet_rows)] z_comp_shares[, frml_check_downup := paste(frml_downup[zero_weigth == FALSE], collapse = " + "), by = c("Child", "year")] frml_prod <- z_comp_shares$frml_prod frml_process_parent <- z_comp_shares$frml_process_parent frml_check_updown <- z_comp_shares$frml_check_updown frml_check_downup <- z_comp_shares$frml_check_downup z_comp_shares[, names(z_comp_shares)[grepl("frml_", names(z_comp_shares))] := NULL] writeFormula(wb, sheet = "SHARES", x = frml_process_parent, startCol = frml_start + 0, startRow = 2) writeFormula(wb, sheet = "SHARES", x = frml_prod, startCol = frml_start + 1, startRow = 2) writeFormula(wb, sheet = "SHARES", x = frml_check_updown, startCol = frml_start + 2, startRow = 2) writeFormula(wb, sheet = "SHARES", x = frml_check_downup, startCol = frml_start + 3, startRow = 2) writeData(wb, "SHARES", cbind("PROCESSED_PARENT", "PRODUCTION", "SUM UPdown", "SUM DOWNup"), startCol = frml_start, colNames = FALSE) addStyle(wb, sheet = "SHARES", style_formula, rows = 1, cols = frml_start:(frml_start + 3)) addStyle(wb, sheet = "SHARES", style_comma, rows = 1:nrow(z_comp_shares) + 1, cols = c(grep("^(production|imports|exports|stockChange|availability|Processed_parent)$", names(z_comp_shares)), frml_start:(frml_start + 3)), gridExpand = TRUE, stack = TRUE) dbg_print(paste("SHARES workbook, save", getwd(), tmp_file_shares)) message("Line 5102") saveWorkbook(wb, tmp_file_shares, overwrite = TRUE) # For testing purposes: #send_mail( # from = "<EMAIL>", # to = swsContext.userEmail, # subject = "Results from SUA_bal_compilation plugin", # body = c("XXXXXXX", tmp_file_shares)) # ##stop("HI!!!!!!!!!!") ## 1 => year = 2014 #i <- 1 dbg_print("starting balancing loop") # XXX Only from 2004 onwards uniqueLevels <- uniqueLevels[timePointYears >= startYear][order(timePointYears)] standData <- vector(mode = "list", length = nrow(uniqueLevels)) for (i in seq_len(nrow(uniqueLevels))) { dbg_print(paste("in balancing loop, start", i)) # For stocks, the first year no need to see back in time. After the first year was done, # stocks may have changed, so opening need to be changed in "data". if (i > 1) { dbg_print(paste("check stocks change in balancing", i)) items_stocks_changed <- unique(standData[[i-1]][!is.na(change_stocks)]$measuredItemSuaFbs) if (length(items_stocks_changed) > 0) { dbg_print(paste("recalculate stocks changed", i)) stocks_modif <- rbind( # Previous data (balanced) rbindlist(standData)[ !is.na(Value) & measuredElementSuaFbs == 'stockChange' & measuredItemSuaFbs %chin% items_stocks_changed, list(geographicAreaM49, timePointYears, measuredItemSuaFbs, delta = Value) ], # New data (unbalanced) data[ !is.na(Value) & timePointYears > unique(standData[[i-1]]$timePointYears) & measuredElementSuaFbs == 'stockChange' & measuredItemSuaFbs %chin% items_stocks_changed, list(geographicAreaM49, timePointYears, measuredItemSuaFbs, delta = Value) ] ) data_for_opening <- dt_left_join( all_opening_stocks[ timePointYears >= startYear & measuredItemFbsSua %chin% items_stocks_changed, .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, new_opening = Value) ], stocks_modif, by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data_for_opening[is.na(delta), delta := 0] data_for_opening <- data_for_opening[order(geographicAreaM49, measuredItemSuaFbs, timePointYears)] dbg_print(paste("update opening stocks", i)) data_for_opening <- update_opening_stocks(data_for_opening) dbg_print(paste("merge data in opening stocks", i)) all_opening_stocks <- dt_left_join( all_opening_stocks, data_for_opening[, .( geographicAreaM49, measuredItemFbsSua = measuredItemSuaFbs, timePointYears, new_opening ) ], by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ) dbg_print(paste("new_opening", i)) all_opening_stocks[ !is.na(new_opening) & (round(new_opening) != round(Value) | is.na(Value)), `:=`( Value = new_opening, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] all_opening_stocks[, new_opening := NULL] } } filter <- uniqueLevels[i, ] sel_vars <- c("geographicAreaM49", "timePointYears") treeSubset <- tree[filter, on = sel_vars] treeSubset[, sel_vars := NULL, with = FALSE] dataSubset <- data[filter, on = sel_vars] dbg_print(paste("actual balancing", i)) standData[[i]] <- newBalancing( data = dataSubset, #nutrientData = subNutrientData, #batchnumber = batchnumber, Utilization_Table = Utilization_Table ) # FIXME: we are now assigning the "Protected" flag to ALL processing as # after the first loop it should have been computed and that value SHOULD # never be touched again. standData[[i]][measuredElementSuaFbs == "foodManufacturing", Protected := TRUE] dbg_print(paste("in balancing loop, end", i)) } all_opening_stocks[, measuredElementSuaFbs := "5113"] dbg_print("end of balancing loop") standData <- rbindlist(standData) calculateImbalance(standData) standData[ supply > 0, imbalance_percent := imbalance / supply * 100 ] # If the imbalance is relatively small (less than 5% in absoulte value) # a new allocation is done, this time with no limits. # Here we need to protect seed, because of its lik to production. standData[measuredElementSuaFbs == "seed", Protected := TRUE] dbg_print("balancing of imbalances < 5%") standData[, small_imb := FALSE] standData[ data.table::between(imbalance_percent, -5, -0.01) | data.table::between(imbalance_percent, 0.01, 5), small_imb := TRUE ] if (nrow(standData[small_imb == TRUE]) > 0) { standData[, can_balance := FALSE] # The following two instructions basically imply to assign the # (small) imbalance with no limits (except food and seed, among utilizations) sel_vars <- c("production", "imports", "exports", "stockChange", "food", "seed") standData[ measuredElementSuaFbs %!in% sel_vars & Protected == FALSE & !is.na(min_threshold), min_threshold := 0 ] standData[ measuredElementSuaFbs %!in% sel_vars & Protected == FALSE & !is.na(max_threshold), max_threshold := Inf ] standData[ !is.na(Value) & Protected == FALSE & !(data.table::between(Value, min_threshold, max_threshold, incbounds = FALSE) %in% FALSE) & !(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange", "foodManufacturing", "seed")), can_balance := TRUE ] standData[, elements_balance := any(can_balance), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] if (nrow(standData[small_imb == TRUE & elements_balance == TRUE]) > 0) { standData[ small_imb == TRUE & elements_balance == TRUE, adjusted_value := balance_proportional(.SD), by = c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs") ] standData[ !is.na(adjusted_value) & adjusted_value != Value, `:=`( Value = adjusted_value, flagObservationStatus = "E", flagMethod = "n" ) ] standData[, adjusted_value := NULL] } } calculateImbalance(standData) standData[ supply > 0, imbalance_percent := round(imbalance / supply * 100,2) ] standData[, `:=` (imbalance = round(imbalance), utilizations = round(utilizations), supply = round(supply)) ] ######################### Save BAL for validation ####################### dbg_print("sua_balanced for validation") sel_vars <- c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs", "measuredElementSuaFbs", "Value", "flagObservationStatus", "flagMethod") sua_balanced <- rbind( data[timePointYears < startYear, sel_vars, with = FALSE], standData[, sel_vars, with = FALSE] ) sua_balanced_aux <- sua_balanced[, .( supply = sum(Value[measuredElementSuaFbs %chin% c("production", "imports")], - Value[measuredElementSuaFbs %chin% c("exports", "stockChange")], na.rm = TRUE), utilizations = sum(Value[!(measuredElementSuaFbs %chin% c("production", "imports", "exports", "stockChange"))], na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ][, imbalance := supply - utilizations ][ supply > 0, imbalance_pct := imbalance / supply * 100 ] sua_balanced_aux <- melt( sua_balanced_aux, c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs"), variable.name = "measuredElementSuaFbs", value.name = "Value" ) sua_balanced_aux[, `:=`(flagObservationStatus = "I", flagMethod = "i")] sua_balanced <- rbind(sua_balanced, sua_balanced_aux) # saveRDS( # sua_balanced, # file.path(R_SWS_SHARE_PATH, "FBSvalidation", COUNTRY, "sua_balanced.rds") # ) ######################### / Save BAL for validation ####################### # saveRDS( # computed_shares_send, # file.path(R_SWS_SHARE_PATH, 'mongeau', paste0('computed_shares_send_', COUNTRY, '.rds')) # ) imbalances <- unique( standData[, list( geographicAreaM49, measuredElementSuaFbs = "5166", measuredItemFbsSua = measuredItemSuaFbs, timePointYears, Value = imbalance, flagObservationStatus = "I", flagMethod = "i", Protected = FALSE ) ] ) imbalances_to_send <- standData[ !is.na(Value) & outside(imbalance, -100, 100) & timePointYears >= startYear, .(country = geographicAreaM49, year = timePointYears, measuredItemSuaFbs, element = measuredElementSuaFbs, value = round(Value), flag = paste(flagObservationStatus, flagMethod, sep = ",")) ] if (nrow(imbalances_to_send) > 0) { imbalances_to_send <- data.table::dcast( imbalances_to_send, country + measuredItemSuaFbs + year ~ element, value.var = c("value", "flag") ) names(imbalances_to_send) <- sub("value_", "", names(imbalances_to_send)) imbalances_to_send <- dt_left_join( imbalances_to_send, unique(standData[, .(country = geographicAreaM49, year = timePointYears, measuredItemSuaFbs, supply, utilizations, imbalance, imbalance_percent)]), by = c("country", "year", "measuredItemSuaFbs") ) d_imbal_info <- imbalances_to_send[, .(country, year, measuredItemSuaFbs, supply = round(supply, 2), imbalance = round(imbalance, 2), perc_imb = round(abs(imbalance / supply) * 100, 2)) ] imbalances_info <- c( all_items = nrow(unique(standData[, .(geographicAreaM49, timePointYears, measuredItemSuaFbs)])), imb_tot = nrow(d_imbal_info), imb_pos_supply = nrow(d_imbal_info[supply > 0]), imb_gt_5percent = nrow(d_imbal_info[supply > 0][perc_imb > 5]), imb_avg_percent = d_imbal_info[supply > 0, mean(abs(perc_imb))] ) setnames(imbalances_to_send, "measuredItemSuaFbs", "measuredItemFbsSua") imbalances_to_send <- nameData('suafbs', 'sua_unbalanced', imbalances_to_send, except = c('measuredElementSuaFbs')) # imbalances_to_send[, measuredItemFbsSua := paste0("'", measuredItemFbsSua)] data_negtrade <- imbalances_to_send[ utilizations == 0 & imbalance < 0 & round(imbalance, 10) == round(supply, 10) ] data_negtrade[, imbalance_percent := NULL] } else { imbalances_to_send <- data.table( info = c("Great, no imbalances!", "Well, at least not greater than 100 tonnes in absolute value") ) data_negtrade <- imbalances_to_send imbalances_info <- c( all_items = 0, imb_tot = 0, imb_pos_supply = 0, imb_gt_5percent = 0, imb_avg_percent = 0 ) } non_existing_for_imputation <- data.table(measuredItemFbsSua = non_existing_for_imputation) non_existing_for_imputation <- nameData('suafbs', 'sua_unbalanced', non_existing_for_imputation) non_existing_for_imputation[, measuredItemFbsSua := paste0("'", measuredItemFbsSua)] # exclude Live animals from output files itemMap <- GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemMap <- itemMap[, .(measuredItemSuaFbs = code, type)] LivestockToExcludeFromFile = itemMap[type %in% c("LSPR", "POPR"), measuredItemSuaFbs] if ("measuredItemFbsSua" %in% names(imbalances_to_send)) { imbalances_to_send = imbalances_to_send[measuredItemFbsSua %!in% LivestockToExcludeFromFile,] } # data_negtrade = data_negtrade[measuredItemFbsSua %!in% LivestockToExcludeFromFile,] # negative_availability = negative_availability[measuredItemFbsSua %!in% LivestockToExcludeFromFile,] wb <- createWorkbook() addWorksheet(wb, "imbalance") writeData(wb, "imbalance", imbalances_to_send) dbg_print(paste("IMBALANCE workbook, save", getwd(), tmp_file_imb)) saveWorkbook(wb, tmp_file_imb, overwrite = TRUE) # write.csv(imbalances_to_send, tmp_file_imb) #write.csv(data_negtrade, tmp_file_NegNetTrade) #write.csv(negative_availability, tmp_file_negative) #write.csv(non_existing_for_imputation, tmp_file_non_exist) #write.csv(fixed_proc_shares, tmp_file_fix_shares) # FIXME: see also the one done for elementToCodeNames codes <- as.data.table(tibble::tribble( ~code, ~name, "5910", "exports", "5520", "feed", "5141", "food", "5023", "foodManufacturing", "5610", "imports", "5165", "industrial", "5016", "loss", "5510", "production", "5525", "seed", "5164", "tourist", "5071", "stockChange" )) standData <- standData[codes, on = c('measuredElementSuaFbs' = 'name')] standData <- standData[, c("geographicAreaM49", "code", "measuredItemSuaFbs", "timePointYears", "Value", "flagObservationStatus", "flagMethod", "Protected"), with = FALSE ] setnames( standData, c("code", "measuredItemSuaFbs"), c("measuredElementSuaFbs", "measuredItemFbsSua") ) standData <- standData[!is.na(Value)] # These cases should not happen (i.e., all flags should already be # set), but in any case, add specific flags so to check. standData[is.na(flagObservationStatus), flagObservationStatus := "M"] standData[is.na(flagMethod), flagMethod := "q"] # Calculate calories calories_per_capita <- dt_left_join( # Food standData[ measuredElementSuaFbs == '5141', list( geographicAreaM49, #measuredElementSuaFbs = "664", measuredItemFbsSua, timePointYears, food = Value, flagObservationStatus = "T", flagMethod = "i" ) ], # Calories nutrientData[, list( geographicAreaM49, measuredItemFbsSua = measuredItemCPC, measuredElementSuaFbs = measuredElement, timePointYears = timePointYearsSP, nutrient = Value ) ], by = c('geographicAreaM49', 'timePointYears', 'measuredItemFbsSua'), allow.cartesian = TRUE ) calories_per_capita <- dt_left_join( calories_per_capita, popSWS[, list(geographicAreaM49, timePointYears, population = Value)], by = c('geographicAreaM49', 'timePointYears') ) data_for_foodGrams<-calories_per_capita[measuredElementSuaFbs=="664"] data_for_foodGrams[,Value:=(food*1000000)/(365*population*1000)] data_for_foodGrams[, c("food", "nutrient", "population") := NULL] data_for_foodGrams[,measuredElementSuaFbs:="665"] data_for_foodGrams[, Protected := FALSE] #Add population in SUA as an item data_pop<-popSWS[,measuredItemFbsSua:="F0001"] data_pop[,`:=`(Protected=TRUE,flagObservationStatus="T",flagMethod="c")] data_pop<-data_pop[timePointYears>=startYear,list(geographicAreaM49,measuredItemFbsSua,timePointYears,flagObservationStatus,flagMethod, measuredElementSuaFbs=measuredElement,Value,Protected)] calories_per_capita_total<-copy(calories_per_capita) calories_per_capita[, Value := food * nutrient / population / 365 * 10] calories_per_capita[, Protected := FALSE] calories_per_capita[, c("food", "nutrient", "population") := NULL] calories_per_capita_total[, Value := food * nutrient/100] calories_per_capita_total[, Protected := FALSE] calories_per_capita_total[, c("food", "nutrient", "population") := NULL] calories_per_capita_total[measuredElementSuaFbs=="664", measuredElementSuaFbs:="261"] calories_per_capita_total[measuredElementSuaFbs=="674", measuredElementSuaFbs:="271"] calories_per_capita_total[measuredElementSuaFbs=="684", measuredElementSuaFbs:="281"] calories_per_capita<-rbind(calories_per_capita,calories_per_capita_total,data_for_foodGrams,data_pop) standData <- rbind( standData, imbalances, all_opening_stocks, calories_per_capita ) standData <- standData[timePointYears >= startYear & !is.na(Value)] standData[, Protected := NULL] ######### Combine old and new calories and data, and get outliers ############# combined_calories <- rbind( data_suabal[measuredElementSuaFbs == "664" & timePointYears < startYear], calories_per_capita[, names(data_suabal), with = FALSE] ) combined_calories <- combined_calories[order(geographicAreaM49, measuredItemFbsSua, timePointYears)] combined_calories <- combined_calories[, `:=`( perc.change = (Value / shift(Value) - 1) * 100, Historical_value_2010_2013 = mean(Value[timePointYears < startYear], na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] combined_calories[, outlier := ""] combined_calories[ (shift(Value) > 5 | Value > 5) & abs(perc.change) > 10 & timePointYears >= startYear, outlier := "OUTLIER", by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] combined_calories <- combined_calories[ unique(combined_calories[outlier == "OUTLIER", .(geographicAreaM49, measuredItemFbsSua)]), on = c("geographicAreaM49", "measuredItemFbsSua") ] old_sua_bal <- data_suabal[timePointYears < startYear] old_sua_bal <- old_sua_bal[, supply := sum( Value[measuredElementSuaFbs %chin% c("5510", "5610")], - Value[measuredElementSuaFbs %chin% c("5910", "5071")], na.rm = TRUE ), by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ] old_sua_bal <- old_sua_bal[ measuredElementSuaFbs %chin% c("5510", "5023", "5016", "5165", "5520", "5525", "5164", "5141") ] old_sua_bal <- old_sua_bal[, .( mean_ratio = mean(Value / supply, na.rm = TRUE), Meanold = mean(Value, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] new_sua_bal <- dt_left_join( standData, old_sua_bal, by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ) new_sua_bal[ measuredElementSuaFbs %chin% c("5510", "5023", "5016", "5165", "5520", "5525", "5164", "5141"), outlier := outside(Value / Meanold, 0.5, 2) ] new_sua_bal[, supply := sum( Value[measuredElementSuaFbs %chin% c("5510", "5610")], - Value[measuredElementSuaFbs %chin% c("5910", "5071")], na.rm = TRUE ), by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ] new_sua_bal[, outl_on_supp := abs(Value / supply - mean_ratio) >= 0.1] new_sua_bal <- new_sua_bal[ measuredElementSuaFbs %chin% c("5510", "5023", "5016", "5165", "5520", "5525", "5164", "5141") ] new_sua_bal <- new_sua_bal[ abs(Meanold - Value) > 10000 & ((measuredElementSuaFbs !=5510 & outlier == TRUE & outl_on_supp == TRUE & Value > 1000 & abs(Meanold - Value) > 10000) | (outlier == TRUE & measuredElementSuaFbs == 5510)) ] if (nrow(new_sua_bal) > 0) { new_sua_bal <- new_sua_bal[, .(geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs, timePointYears, Historical_value_2010_2013 = Meanold, outlier = "OUTLIER") ] sel_vars <- c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") out_elems_items <- rbind( data_suabal[timePointYears < startYear][unique(new_sua_bal[, sel_vars, with = FALSE]), on = sel_vars], standData[unique(new_sua_bal[, sel_vars, with = FALSE]), on = sel_vars] ) out_elems_items <- dt_left_join( out_elems_items, new_sua_bal, by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs", "timePointYears") ) out_elems_items[is.na(outlier), outlier := ""] out_elems_items[, Historical_value_2010_2013 := unique(na.omit(Historical_value_2010_2013)), c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] out_elems_items <- out_elems_items[order(geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs, timePointYears)] out_elems_items[, perc.change := (Value / shift(Value) - 1) * 100, by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] } else { out_elems_items <- new_sua_bal[0, .(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value, flagObservationStatus, flagMethod, perc.change = NA_real_, Historical_value_2010_2013 = NA_real_, outlier)] } out_elems_items <- rbind(combined_calories, out_elems_items, fill = TRUE) out_elems_items[, Value := round(Value, 2)] out_elems_items[, perc.change := round(perc.change, 2)] out_elems_items[, Historical_value_2010_2013 := round(Historical_value_2010_2013, 2)] tmp_file_outliers <- file.path(TMP_DIR, paste0("OUTLIERS_", COUNTRY, ".csv")) out_elems_items <- nameData("suafbs", "sua_unbalanced", out_elems_items, except = "timePointYears") write.csv(out_elems_items, tmp_file_outliers) message("Line 5462") ######### / Combine old and new calories and data, and get outliers ########### if (nrow(data_suabal[timePointYears >= startYear]) > 0) { sel_vars <- c('geographicAreaM49', 'measuredElementSuaFbs', 'measuredItemFbsSua', 'timePointYears') data_suabal_missing <- data_suabal[timePointYears >= startYear][!standData, on = sel_vars] if (nrow(data_suabal_missing) > 0) { data_suabal_missing[, `:=`( Value = NA_real_, flagObservationStatus = NA_character_, flagMethod = NA_character_ ) ] standData <- rbind(standData, data_suabal_missing) } } ######### LOSS RATIO CHECK ######### livia if(nrow(standData > 0) & "5016" %in% unique(standData$measuredElementSuaFbs)){ losses_processedData <- copy(standData) losses_processedData <- losses_processedData[measuredElementSuaFbs %in% c("5510", "5610", "5016"),] setnames(losses_processedData, c("measuredItemFbsSua","measuredElementSuaFbs"), c("measuredItemCPC","measuredElement")) losses_processedData <- denormalise( normalisedData = losses_processedData, denormaliseKey = "measuredElement", fillEmptyRecords = TRUE ) losses_processedData[, Value_measuredElement_5126 := Value_measuredElement_5016 / (sum(Value_measuredElement_5510, Value_measuredElement_5610, na.rm = TRUE)), by = c("geographicAreaM49","measuredItemCPC", "timePointYears")] losses_processedData[, flagObservationStatus_measuredElement_5126 := flagObservationStatus_measuredElement_5016] losses_processedData[, flagMethod_measuredElement_5126 := flagMethod_measuredElement_5016] losses_normalisedData <- normalise(losses_processedData) losses_threshold <- losses_normalisedData[measuredElement %in% "5126" & Value >= 0.3,] setnames(losses_threshold, c("measuredItemCPC","measuredElement"),c("measuredItemFbsSua","measuredElementSuaFbs")) losses_threshold <- nameData("suafbs", "sua_balanced", losses_threshold, except = c("measuredElementSuaFbs", "timePointYears")) losses_threshold[, measuredElementSuaFbs := "Loss Ratio %"] wb <- createWorkbook() addWorksheet(wb, "losses_to_check") writeData(wb, "losses_to_check", losses_threshold) dbg_print(paste("Losses workbook, save", getwd(), tmp_file_losses_to_check)) saveWorkbook(wb, tmp_file_losses_to_check, overwrite = TRUE) } #### INDUSTRIAL TO CHECK #####################################à #tmp_file_industrial_to_check <- file.path(TMP_DIR, paste0("INDUSTRIAL_TO_CHECK_", COUNTRY, ".xlsx")) if(nrow(standData > 0) & "5165" %in% unique(standData$measuredElementSuaFbs)){ industrial_processedData <- copy(standData) industrial_processedData <- industrial_processedData[measuredElementSuaFbs %in% c("5165"),] not_industrial_table <- ReadDatatable("not_industrial_use_table") industrial_processedData <- merge(industrial_processedData, not_industrial_table[, c("cpc_code","not_industrial"), with = F], all.x = T, by.x = "measuredItemFbsSua", by.y = "cpc_code") industrial_processedData <- industrial_processedData[not_industrial %in% "message",] industrial_processedData <- industrial_processedData[Value > 0 & !is.na(Value),] industrial_processedData <- unique(industrial_processedData[, c("measuredItemFbsSua", "geographicAreaM49", "measuredElementSuaFbs"), with = F]) industrial_processedData <- nameData("suafbs", "sua_balanced", industrial_processedData) wb <- createWorkbook() addWorksheet(wb, "industrial_to_check") writeData(wb, "industrial_to_check", industrial_processedData) dbg_print(paste("Industrial workbook, save", getwd(), tmp_file_industrial_to_check)) saveWorkbook(wb, tmp_file_industrial_to_check, overwrite = TRUE) } ########## DES calculation sel_vars <- c('geographicAreaM49', 'timePointYears', 'measuredItemFbsSua') des <- rbind( data_suabal[ measuredElementSuaFbs == '664' & timePointYears %in% 2010:(startYear-1), .(Value = sum(Value, na.rm = TRUE)), by = sel_vars ], standData[ measuredElementSuaFbs == '664' & timePointYears >= startYear, .(Value = sum(Value, na.rm = TRUE)), by = sel_vars ] ) des <- rbind( des, des[, .(measuredItemFbsSua = 'S2901', Value = sum(Value)), by = c('geographicAreaM49', 'timePointYears') ] ) des[, Value := round(Value, 2)] f_des <- file.path(R_SWS_SHARE_PATH, "FBSvalidation", COUNTRY, "des.rds") if (file.exists(f_des)) { file.copy(f_des, sub("des\\.rds", "des_prev.rds", f_des)) } # saveRDS(des, f_des) ##### Plot of main DES absolute variations des_diff <- des[ order(geographicAreaM49, measuredItemFbsSua, timePointYears), .(year = timePointYears, diff = Value - shift(Value)), .(geographicAreaM49, item = measuredItemFbsSua) ][ year != min(year) ] des_diff <- des_diff[item %chin% des_diff[abs(diff) > 20]$item] des_diff[item == "S2901", item := "GRAND TOTAL"] # plot_main_des_diff <- # ggplot(des_diff, aes(x = year, diff, group = item, color = item)) + # geom_line(size = 1) + # geom_point(size = 3) + # ggtitle("Absolute variation of DES and main variations of items", # subtitle = COUNTRY_NAME) # # tmp_file_plot_main_des_diff <- # file.path(TMP_DIR, paste0("PLOT_MAIN_DES_DIFF_", COUNTRY, ".pdf")) # # ggsave(tmp_file_plot_main_des_diff, plot = plot_main_des_diff) ##### / Plot of main DES absolute variations # ##### Plot of main DES # main_des_items <- des[, .(geographicAreaM49, year = timePointYears, item = measuredItemFbsSua, Value) ][ item %chin% des[Value > 100]$measuredItemFbsSua ][ order(geographicAreaM49, item, year) ] main_des_items[item == "S2901", item := "GRAND TOTAL"] # plot_main_des_items <- # ggplot(main_des_items, aes(x = year, Value, group = item, color = item)) + # geom_line(size = 1) + # geom_point(size = 3) + # ggtitle("Main DES items (> 100 Calories)", subtitle = COUNTRY_NAME) # # tmp_file_plot_main_des_items <- # file.path(TMP_DIR, paste0("PLOT_MAIN_DES_ITEMS_", COUNTRY, ".pdf")) # # ggsave(tmp_file_plot_main_des_items, plot = plot_main_des_items) # ##### / Plot of main DES # ##### Plot of main diff avg DES des_main_diff_avg <- des[ measuredItemFbsSua != "S2901", .(pre = mean(Value[timePointYears < startYear]), post = mean(Value[timePointYears >= startYear])), by = c("geographicAreaM49", "measuredItemFbsSua") ] des_main_diff_avg <- des_main_diff_avg[abs(post - pre) > 20] des_main_diff_avg <- melt(des_main_diff_avg, c("geographicAreaM49", "measuredItemFbsSua")) des_main_diff_avg <- nameData("suafbs", "sua_unbalanced", des_main_diff_avg, except = "geographicAreaM49") # plot_des_main_diff_avg <- # ggplot(des_main_diff_avg, # aes(x = measuredItemFbsSua_description, y = value, # group = rev(variable), fill = variable)) + # geom_col(position = "dodge") + # coord_flip() + # ggtitle("Main diff (> 20 Cal) in DES average pre (< startYear) and post (>= startYear)", # subtitle = COUNTRY_NAME) # # # tmp_file_plot_des_main_diff_avg <- # file.path(TMP_DIR, paste0("PLOT_DES_MAIN_DIFF_AVG_", COUNTRY, ".pdf")) # # ggsave(tmp_file_plot_des_main_diff_avg, plot = plot_des_main_diff_avg) # # ##### Plot of main diff avg DES # des_cast <- data.table::dcast( des, geographicAreaM49 + measuredItemFbsSua ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) des_cast <- nameData("suafbs", "sua_balanced", des_cast) setorderv(des_cast, names(des_cast)[ncol(des_cast)], order = -1) # Main items, more then 90% des_main_90 <- des[ measuredItemFbsSua != "S2901" & timePointYears >= startYear, .(tot = sum(Value)), by = c("geographicAreaM49", "measuredItemFbsSua") ][ order(-tot) ][, cumsum := cumsum(tot) ] des_main_90 <- des_main_90[ des[ measuredItemFbsSua != "S2901" & timePointYears >= startYear, .(maintot = sum(Value)), by = "geographicAreaM49" ], on = "geographicAreaM49" ][ cumsum < maintot * 0.9 ][, c("tot", "cumsum", "maintot") := NULL ] des_main <- rbind( des_cast[measuredItemFbsSua == "S2901"], des_cast[des_main_90, on = c("geographicAreaM49", "measuredItemFbsSua")] ) des_main <- rbind( des_main, des_main[, lapply(.SD, function(x) round(sum(x[-1]) / x[1] * 100, 2)), .SDcols = c(sort(unique(des$timePointYears))) ], fill = TRUE ) des_main[ is.na(measuredItemFbsSua), measuredItemFbsSua_description := "PERCENTAGE OF MAIN OVER TOTAL" ] ########## create XLSX for main DES items des_main_90_and_tot <- rbind( data.table( geographicAreaM49 = unique(des_main_90$geographicAreaM49), measuredItemFbsSua = "S2901" ), des_main_90 ) des_level_diff <- des[ order(geographicAreaM49, measuredItemFbsSua, timePointYears), .( Value = Value - shift(Value), timePointYears ), by = c("geographicAreaM49", "measuredItemFbsSua") ] des_level_diff_cast <- data.table::dcast( des_level_diff, geographicAreaM49 + measuredItemFbsSua ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) des_perc_diff <- des[ order(geographicAreaM49, measuredItemFbsSua, timePointYears), .( Value = Value / shift(Value) - 1, timePointYears = timePointYears ), by = c("geographicAreaM49", "measuredItemFbsSua") ] des_perc_diff[is.infinite(Value) | is.nan(Value), Value := NA_real_] des_perc_diff_cast <- data.table::dcast( des_perc_diff, geographicAreaM49 + measuredItemFbsSua ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) sel_vars <- c("geographicAreaM49", "geographicAreaM49_description", "measuredItemFbsSua", "measuredItemFbsSua_description") by_vars <- c("geographicAreaM49", "measuredItemFbsSua") des_level_diff_cast <- merge(des_level_diff_cast, des_cast[, sel_vars, with = FALSE ], by = by_vars) setcolorder(des_level_diff_cast, names(des_cast)) des_perc_diff_cast <- merge(des_perc_diff_cast, des_cast[, sel_vars, with = FALSE], by = by_vars) setcolorder(des_perc_diff_cast, names(des_cast)) des_level_diff_cast <- des_level_diff_cast[des_main_90_and_tot, on = by_vars] des_perc_diff_cast <- des_perc_diff_cast[des_main_90_and_tot, on = by_vars] wb <- createWorkbook() addWorksheet(wb, "DES_MAIN") addWorksheet(wb, "DES_MAIN_diff") addWorksheet(wb, "DES_MAIN_diff_perc") writeData(wb, "DES_MAIN", des_main) writeData(wb, "DES_MAIN_diff", des_level_diff_cast) writeData(wb, "DES_MAIN_diff_perc", des_perc_diff_cast) style_cal_0 <- createStyle(fgFill = "black", fontColour = "white", textDecoration = "bold") style_cal_gt_10 <- createStyle(fgFill = "lightyellow") style_cal_gt_20 <- createStyle(fgFill = "yellow") style_cal_gt_50 <- createStyle(fgFill = "orange") style_cal_gt_100 <- createStyle(fgFill = "red") style_percent <- createStyle(numFmt = "PERCENTAGE") style_mean_diff <- createStyle(borderColour = "blue", borderStyle = "double", border = "TopBottomLeftRight") # All zeros in 2014-2018, that were not zeros in 2010-2013 zeros <- des_main[, .SD, .SDcols = as.character(yearVals)] == 0 & des_main[, rowMeans(.SD), .SDcols = as.character(2010:(startYear-1))] > 0 for (i in which(names(des_level_diff_cast) %in% 2011:endYear)) { addStyle(wb, "DES_MAIN", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 10], style = style_cal_gt_10, gridExpand = TRUE) addStyle(wb, "DES_MAIN", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 20], style = style_cal_gt_20, gridExpand = TRUE) addStyle(wb, "DES_MAIN", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 50], style = style_cal_gt_50, gridExpand = TRUE) addStyle(wb, "DES_MAIN", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 100], style = style_cal_gt_100, gridExpand = TRUE) if (names(des_level_diff_cast)[i] %in% yearVals) { j <- names(des_level_diff_cast)[i] rows_with_zero <- zeros[, j] if (any(rows_with_zero == TRUE)) { addStyle(wb, "DES_MAIN", cols = i, rows = 1 + (1:nrow(zeros))[zeros[, j]], style = style_cal_0, gridExpand = TRUE) } } addStyle(wb, "DES_MAIN_diff", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 10], style = style_cal_gt_10, gridExpand = TRUE) addStyle(wb, "DES_MAIN_diff", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 20], style = style_cal_gt_20, gridExpand = TRUE) addStyle(wb, "DES_MAIN_diff", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 50], style = style_cal_gt_50, gridExpand = TRUE) addStyle(wb, "DES_MAIN_diff", cols = i, rows = 1 + (1:nrow(des_level_diff_cast))[abs(des_level_diff_cast[[i]]) > 100], style = style_cal_gt_100, gridExpand = TRUE) } high_variation_mean <- abs(des_main[, rowMeans(.SD), .SDcols = as.character(2010:(startYear-1))] / des_main[, rowMeans(.SD), .SDcols = as.character(yearVals)] - 1) > 0.30 if (any(high_variation_mean == TRUE)) { high_variation_mean <- 1 + (1:nrow(des_main))[high_variation_mean] addStyle(wb, sheet = "DES_MAIN", style_mean_diff, rows = high_variation_mean, cols = which(names(des_level_diff_cast) %in% yearVals), gridExpand = TRUE, stack = TRUE) } addStyle(wb, sheet = "DES_MAIN_diff_perc", style_percent, rows = 1:nrow(des_level_diff_cast) + 1, cols = which(names(des_level_diff_cast) %in% 2011:endYear), gridExpand = TRUE, stack = TRUE) setColWidths(wb, "DES_MAIN", 4, 40) setColWidths(wb, "DES_MAIN_diff", 4, 40) setColWidths(wb, "DES_MAIN_diff_perc", 4, 40) tmp_file_des_main <- file.path(TMP_DIR, paste0("DES_MAIN_ITEMS_", COUNTRY, ".xlsx")) message("Line 5807") saveWorkbook(wb, tmp_file_des_main, overwrite = TRUE) ########## / create XLSX for main DES items tmp_file_des <- file.path(TMP_DIR, paste0("DES_", COUNTRY, ".csv")) #des_cast[, measuredItemFbsSua := paste0("'", measuredItemFbsSua)] write.csv(des_cast, tmp_file_des) ########## / DES calculation # Nutrients (except 664), are required only in last round (when saving) if (!(TRUE %in% swsContext.computationParams$save_nutrients)) { standData <- standData[measuredElementSuaFbs %!in% c('261', '271', '281', '674', '684')] } out <- SaveData(domain = "suafbs", dataset = "sua_balanced", data = standData, waitTimeout = 20000) if (exists("out")) { body_message <- sprintf( "Plugin completed in %1.2f minutes. ################################################ # Imbalances (greater than 100 t in abs value) # ################################################ unbalanced items: %s (out of %s) unbalanced items for items with positive supply: %s unbalanced items for items with imbalance > 5%%: %s average percent imbalance in absolute value: %1.2f ############################################### ############ Parameters ########### ############################################### country = %s thresold method = %s fill_extraction_rates= %s ############################################### ########### ShareDownUp ########### ############################################### shareDownUp can be modified here: %s ############################################### ############## Removed feed ############### ############################################### The following NEW feed items were removed as including them would have created a huge negative imbalance: %s The following NEW feed items are dubious, they might be removed, but you will need to do it manually: %s ############################################### ############## Flags ############## ############################################### E,-: Balancing: utilization modified OR Processed created down up using official data E,b: Final balancing (industrial, Feed) E,c: Balancing: production modified to compensate net trade E,e: Outlier replaced E,h: Balancing: imbalance to food, given food is only utilization -Food Residual E,i: Food processed generated, using availability E,n: Balancing of small imbalances OR Stock variation corrected for over accumulation(to change) E,s: Balancing: stocks modified E,u: Stocks variation generated by the model OR updated opening stocks I,c: Derived production generated I,e: Module imputation I,i: Residual item (identity) OR stocks as 20 percent of supply in 2013 I,-: Opening stocks as cumulated stocks variations 1961-2013 M,q: Cases for which flags were not set (should never happen) T,i: Calories per capita created T,p: Oilworld stocks data T,h: USDA stocks data ############################################### ############## Files ############## ############################################### The following files are attached: - DES_MAIN_ITEMS_*.xlsx = as DES_*.csv, but only with items that accounted for nearly 90%% on average over 2014-2018 - DES_*.csv = calculation of DES (total and by items) - OUTLIERS_*.csv = outliers in Calories (defined as those that account for more than 5 Calories with an increase of more than 15%%) - SHARES_*.xlsx = Parents/Children shares, availability, etc. - IMBALANCE_*.csv = imbalances, supply and utilizations - LOSSES_TO_CHECK.xlsx = items with loss ratio bigger than 30%% - NEW_ELEMENTS_*.csv = elements that appear for the first time - STOCK_CORRECTION_*.csv = Corrected Stocks ", difftime(Sys.time(), start_time, units = "min"), imbalances_info[['imb_tot']], prettyNum(imbalances_info[['all_items']], big.mark = ","), imbalances_info[['imb_pos_supply']], imbalances_info[['imb_gt_5percent']], imbalances_info[['imb_avg_percent']], COUNTRY, THRESHOLD_METHOD, FILL_EXTRACTION_RATES, sub('/work/SWS_R_Share/', '', shareDownUp_file), msg_new_feed_remove, msg_new_feed_dubious ) if (!CheckDebug()) { send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Results from SUA_bal_compilation plugin", body = c(body_message, # tmp_file_plot_main_des_items, # tmp_file_plot_main_des_diff, # tmp_file_plot_des_main_diff_avg, tmp_file_des_main, tmp_file_des, tmp_file_outliers, tmp_file_shares, tmp_file_imb, tmp_file_losses_to_check, tmp_file_industrial_to_check, #tmp_file_extr, #tmp_file_negative, #tmp_file_non_exist, tmp_file_new, #tmp_file_fix_shares, #tmp_file_NegNetTrade, tmp_file_Stock_correction ) ) } unlink(TMP_DIR, recursive = TRUE) out[c("inserted", "appended", "ignored", "discarded")] <- lapply( out[c("inserted", "appended", "ignored", "discarded")], function(x) ifelse(is.na(x[[1]]), 0, x[[1]]) ) last_msg <- paste(out$inserted + out$appended, "observations written") if (out$discarded + out$ignored > 0) { last_msg <- paste(last_msg, "and issues with", out$discarded + out$ignored) } f <- file.path(R_SWS_SHARE_PATH, "FBSvalidation", "reference", "plugin_success.txt") if (file.exists(f)) { f <- read.delim(f, header = FALSE, stringsAsFactors = FALSE) last_msg <- paste0("<div>", last_msg, "</div><br />", "<div style = \"color: red; font-size: 20px; text-align: center;\">", f[, sample(2:ncol(f), 1)][1], "</div><br /><div style = \"color: red; font-size: 20px; background-size: ", "300px 200px; width: 300; height: 200px; background-image: url('", f[1, 1], "')\"></div>") } print(last_msg) } else { print("The SUA_bal_compilation plugin had a problem when saving data.") } <file_sep>/modules/outlierImputation/main.R ##' # Pull data from different domains to sua ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to identify outliers in feed, seed and loss figures at sua unbalanced level ##' ##' ##' **Inputs:** ##' ##' * sua unbalanced ##' ##' **Flag assignment:** ##' ##' I e ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) #library(faoswsStandardization) library(faoswsFlag) if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("C:/Users/modules/outlierImputation") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) startYear = as.numeric(2011) #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2017) #years to consider for outlier detections startYearOutl = as.numeric(swsContext.computationParams$startYearoutl) endYearOutl = as.numeric(swsContext.computationParams$endYearoutl) yearValsOutl = startYearOutl:endYearOutl #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2017) geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] selectedGEOCode =sessionCountries ######################################### ##### Pull from SUA unbalanced data ##### ######################################### message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredElementSuaFbs") eleKeys = eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = c("5510","5610","5071","5023","5910","5016","5165","5520","5525","5164","5166","5141","664","5113")) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) data = GetData(key,omitna = F, normalized=T) #write.csv(data, "data_before_outlier_plugin.csv", row.names = F) ##adding missing lines data2014_2017<-data %>% dplyr::filter(timePointYears>=2014 & timePointYears<=2017) data2011_2013<-data %>% dplyr::filter(timePointYears>=2011 & timePointYears<=2013) data2<-dcast(data, formula = geographicAreaM49+ measuredElementSuaFbs+ measuredItemFbsSua ~ timePointYears, value.var = "Value") data3<-melt(data2, id.vars = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua")) data3$variable<-as.character(data3$variable) data3<-data3 %>% dplyr::filter(is.na(value) & variable>=2014 & variable<=2017 & (measuredElementSuaFbs==5520|measuredElementSuaFbs==5525|measuredElementSuaFbs==5016|measuredElementSuaFbs==5165)) data3[,"coladd"]<-"E" data3[,"coladd2"]<-"e" data3<-as.data.table(data3) data4<-data3[,colnames(data)] setnames(data3, data4) data2014_2017<-data2014_2017 %>% dplyr::filter(!is.na(Value)) datafinal<-rbind(data2011_2013, data2014_2017, data3) data<-datafinal #miss<-data %>% filter(measuredElementSuaFbs==5520|measuredElementSuaFbs==5525|measuredElementSuaFbs==5165) #miss<- miss %>% group_by(geographicAreaM49,measuredItemFbsSua) %>% mutate(Meanold=mean(Value[timePointYears<2014],na.rm=T)) #miss$Meanold[is.na(miss$Meanold)]<-0 #miss<-miss %>% filter(Meanold!=0) #miss<- miss %>% group_by(geographicAreaM49,measuredItemFbsSua, measuredElementSuaFbs) %>% mutate(sumyears=sum(as.integer(timePointYears[timePointYears>=2014]))) ################# get protected flags protectedFlags<-ReadDatatable(table = "valid_flags") keys = c("flagObservationStatus", "flagMethod") commDef=ReadDatatable("fbs_commodity_definitions") # primaryProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | primary_commodity=="X"]] primary=commDef$cpc[commDef[,primary_commodity=="X"]] ProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X"]] food=commDef$cpc[commDef[,food_item=="X"]] ########################################################### ##### calculate historical ratios ##### ########################################################### sua_unb<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(Meanold=mean(Value[timePointYears<2014],na.rm=T)) sua_unb$Meanold[is.na(sua_unb$Meanold)]<-0 sua_unb$Value[is.na(sua_unb$Value)]<-0 sua_unb$flagObservationStatus[is.na(sua_unb$Value)]<-0 sua_unb <- merge(sua_unb, protectedFlags, by = keys) ##Added by Valdivia attach(sua_unb) sua_unb$Protected[flagObservationStatus=="E" & flagMethod %in% c("e","f")]<-FALSE ## sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(prod=sum(Value[measuredElementSuaFbs==5510])) sua_unb$prod[is.na(sua_unb$prod)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(imp=sum(Value[measuredElementSuaFbs==5610])) sua_unb$imp[is.na(sua_unb$imp)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(exp=sum(Value[measuredElementSuaFbs==5910])) sua_unb$exp[is.na(sua_unb$exp)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp-exp) sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio=Value/supply) sua_unb$ratio[sua_unb$ratio<0]<-NA sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) sua_unb<- sua_unb %>% dplyr::mutate(Diff_val=Value-Meanold) sua_unb<-as.data.table(sua_unb) sua_unb[, mean_ratio2 := ifelse(mean_ratio>1, 1, mean_ratio)] utiLARGERsup<-sua_unb %>% dplyr::filter(mean_ratio>1 & (measuredElementSuaFbs==5520|measuredElementSuaFbs==5525|measuredElementSuaFbs==5165|measuredElementSuaFbs==5016)) ## feed feed<-sua_unb %>% dplyr::filter(measuredElementSuaFbs==5520 & abs(supply)>0) feed=data.table(feed) ##following row changed by Valdivia to balance items where feed is the only utilization feed <- feed %>% dplyr::mutate( outl = abs(ratio-mean_ratio) > 0.1 | mean_ratio==1 | mean_ratio>1| (mean_ratio!=0 & ratio==0) | ((Value>2*Meanold | Value<0.5*Meanold) & (Diff_val > 10000 | Diff_val < -10000)) ) outl_feed<-feed %>% dplyr::filter((outl==T & timePointYears%in%yearValsOutl) ) impute_feed<-outl_feed %>% dplyr::filter(supply>=0 & mean_ratio>=0 & Protected==F ) #outl_feed %>% filter(supply<0 | mean_ratio<0 | mean_ratio>1) %>% write.csv( file = "feed_to_check.csv") impute_feed<-impute_feed %>% dplyr::mutate(impute=supply*mean_ratio2) #impute_feed %>% write.csv( file = "feed_outliers.csv") colnames(impute_feed)[7]<-"pippo" colnames(impute_feed)[20]<-"Value" impute_feed<-impute_feed[,colnames(data)] if (nrow(impute_feed)> 0) { impute_feed[,6]<-c("E") impute_feed[,7]<-c("e") } ## seed careful ratio of seed is measured over production sua_unb2<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio=Value/supply) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) seed<-sua_unb2 %>% dplyr::filter(measuredElementSuaFbs==5525) seed <- seed %>% dplyr::mutate( mean_ratio2 = ifelse(mean_ratio > 1, 1, mean_ratio), outl = abs(ratio-mean_ratio) > 0.05 | mean_ratio==1 | mean_ratio>1 | (mean_ratio!=0 & ratio==0) | ((Value>2*Meanold | Value<0.5*Meanold) & (Diff_val > 10000 | Diff_val < -10000)) ) outl_seed<-seed %>% dplyr::filter((outl==T & timePointYears%in%yearValsOutl) ) impute_seed<-outl_seed %>% dplyr::filter(supply>=0 & mean_ratio>=0 & Protected==F ) #outl_feed %>% filter(supply<0 | mean_ratio<0 | mean_ratio>1) %>% write.csv( file = "feed_to_check.csv") impute_seed<-impute_seed %>% dplyr::mutate(impute=supply*mean_ratio2) #impute_feed %>% write.csv( file = "feed_outliers.csv") colnames(impute_seed)[7]<-"pippo" colnames(impute_seed)[20]<-"Value" impute_seed<-impute_seed[,colnames(data)] if (nrow(impute_seed)> 0) { impute_seed[,6]<-c("E") impute_seed[,7]<-c("e") } rm(sua_unb2) ## loss careful supply definition changes sua_unb2<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio=Value/supply) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) loss<-sua_unb2 %>% dplyr::filter(measuredElementSuaFbs==5016) loss <- loss %>% dplyr::mutate( mean_ratio2 = ifelse(mean_ratio > 1, 1, mean_ratio), outl = abs(ratio-mean_ratio) > 0.05 |mean_ratio>1| ((Value>2*Meanold | Value<0.5*Meanold) & (Diff_val > 10000 | Diff_val < -10000)) ) outl_loss<-loss %>% dplyr::filter((outl==T & timePointYears%in%yearValsOutl) ) impute_loss<-outl_loss %>% dplyr::filter(supply>=0 & mean_ratio>0 & Protected==F & measuredItemFbsSua %in% food & measuredItemFbsSua %in% primaryProxyPrimary) impute_loss<-impute_loss %>% dplyr::mutate(impute=supply*mean_ratio2) colnames(impute_loss)[7]<-"pippo" colnames(impute_loss)[20]<-"Value" impute_loss<-impute_loss[,colnames(data)] if (nrow(impute_loss)> 0) { impute_loss[,6]<-c("E") impute_loss[,7]<-c("e") } ##### INDUSTRIAL ## ind ind<-sua_unb %>% dplyr::filter(measuredElementSuaFbs==5165) ind <- ind %>% dplyr::mutate( outl = abs(ratio-mean_ratio) > 0.05 | mean_ratio==1 | mean_ratio>1| (mean_ratio!=0 & ratio==0) | ((Value>2*Meanold | Value<0.5*Meanold) & (Diff_val > 10000 | Diff_val < -10000)) ) outl_ind<-ind %>% dplyr::filter((outl==T & timePointYears%in%yearValsOutl) ) impute_ind<-outl_ind %>% dplyr::filter(supply>=0 & mean_ratio>=0 & Protected==F ) #outl_feed %>% filter(supply<0 | mean_ratio<0 | mean_ratio>1) %>% write.csv( file = "feed_to_check.csv") impute_ind<-impute_ind %>% dplyr::mutate(impute=supply*mean_ratio2) #impute_feed %>% write.csv( file = "feed_outliers.csv") colnames(impute_ind)[7]<-"pippo" colnames(impute_ind)[20]<-"Value" impute_ind<-impute_ind[,colnames(data)] if (nrow(impute_loss)> 0) { impute_ind[,6]<-c("E") impute_ind[,7]<-c("e") } impute_feed<-as.data.table(impute_feed) impute_seed<-as.data.table(impute_seed) impute_loss<-as.data.table(impute_loss) impute_ind<-as.data.table(impute_ind) ################################################################ ##### save data ##### ################################################################ impute=rbind(impute_feed,impute_seed,impute_loss,impute_ind) impute<-impute %>% dplyr::filter(Value!=0) out<-as.data.table(impute) ################################################################ ##### save data ##### ################################################################ utiLARGERsup$timePointYears<-NULL utiLARGERsup$Value<-NULL utiLARGERsup$prod<-NULL utiLARGERsup$imp<-NULL utiLARGERsup$exp<-NULL utiLARGERsup$supply<-NULL utiLARGERsup$ratio<-NULL utiLARGERsup$Diff_val<-NULL utiLARGERsup$mean_ratio2<-NULL utiLARGERsup$Valid<-NULL utiLARGERsup$Protected<-NULL utiLARGERsup$Meanold<-NULL utiLARGERsup$flagMethod<-NULL utiLARGERsup$flagObservationStatus<-NULL utiLARGERsup<-unique(utiLARGERsup) if (nrow(out) > 0) { stats = SaveData(domain = "suafbs", dataset = "sua_unbalanced", data = out, waitTimeout = 2000000) paste0(stats$inserted, " observations written, ", stats$ignored, " weren't updated, ", stats$discarded, " had problems.") ################################################################ ##### send Email with notification of correct execution ##### ################################################################ ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "Outlier plug-in has correctly run" body = "The plug-in has replaced outliers and saved imputed values in your session" sendmailR::sendmail(from, to, subject , body) paste0("Email sent to ", swsContext.userEmail) } else { print("No outliers were detected and replaced.") } setDT(utiLARGERsup) bodyOutliers= paste("The Email contains a list of items with one or more utilizations that historically were larger than supply.", sep='\n') sendMailAttachment(utiLARGERsup,"Util_larger_supply",bodyOutliers) <file_sep>/modules/treeCheck/main.R suppressMessages({ library(data.table) library(faosws) library(faoswsFlag) library(faoswsUtil) library(faoswsImputation) library(faoswsProduction) library(faoswsProcessing) library(faoswsEnsure) library(magrittr) library(dplyr) library(sendmailR) library(faoswsStandardization) library(stringr) }) # top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) R_SWS_SHARE_PATH <- Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ library(faoswsModules) SETTINGS = ReadSettings("modules/treeCheck/sws.yml") ## If you're not on the system, your settings will overwrite any others R_SWS_SHARE_PATH = SETTINGS[["share"]] ## Define where your certificates are stored SetClientFiles(SETTINGS[["certdir"]]) ## Get session information from SWS. Token must be obtained from web interface GetTestEnvironment(baseUrl = SETTINGS[["server"]], token = SETTINGS[["token"]]) dir=paste0("C:/Work/SWS/FBS/Production/DerivedProduction/Output/") } sessionKey = swsContext.datasets[[1]] ########################################################################################################### ##'This are those commodity that are pubblished on FAOSTAT ##'I build the key, always the same in the PRODUCTION sub modules: ##completeImputationKey=getCompleteImputationKey("production") FBScountries=ReadDatatable("fbs_countries")[,code] FBSItems=ReadDatatable("fbs_tree")[,item_sua_fbs] fclmapping=ReadDatatable("fcl_2_cpc") countrymapping=ReadDatatable("fal_2_m49") ##---------------------------------------------------------------------------------------------------------- ##' Get default parameters params = defaultProcessedItemParams() processedCPC=ReadDatatable("processed_item")[,measured_item_cpc] toBePubblished=ReadDatatable("processed_item")[faostat==TRUE,measured_item_cpc] ############################################################################################################# ##' Get the commodity tree from the TREE DATASET: ##' The country dimention depends on the session: geoImputationSelection = swsContext.computationParams$geom49 sessionCountry=getQueryKey("geographicAreaM49", sessionKey) selectedCountry = switch(geoImputationSelection, "session" = sessionCountry, "all" = FBScountries) #selectedCountry = "233" ##--------------------------------------------------------------------------------------------------------- ##' Get the list of processed items to impute #ItemImputationSelection = swsContext.computationParams$Items #sessionItems=getQueryKey("measuredItemFbsSua", sessionKey) sessionItems = FBSItems ##' The year dimention depends on the session: startYear=2000 # imputationStartYear = startYear #imputationStartYear=swsContext.computationParams$startImputation endYear=2013 areaKeys=selectedCountry ##'Check on the consistency of startYear, andYear if(startYear>=endYear){ stop("You must select startYear lower than endYear") } timeKeys=as.character(c(2000:2013)) # if(!(imputationStartYear>=startYear & imputationStartYear<=endYear)){ # stop("imputationStartYear must lie in the time window between startYear and EndYear") # } ##' I have to pull all the items in the parent and child columns: itemKeysParent=GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemParentCPC_tree")[,code] itemKeysChild=GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemChildCPC_tree")[,code] ##' To save time I pull just the only element I need: "extraction rate" whose code is 5423 elemKeys=c("5423") #allCountries=GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "geographicAreaM49")[,code] ##' Seven Pilot countries # allCountries=c("454", "686", "1248", "716","360", "392", "484") # allCountries=c("56") allLevels=list() forValidationFile=list() #logConsole1=file("modules/processedItems/logProcessed.txt",open = "w") #sink(file = logConsole1, append = TRUE, type = c( "message")) itemKeysChild[itemKeysChild] #%in% processedCPC keyTree = DatasetKey(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemParentCPC_tree = Dimension(name = "measuredItemParentCPC_tree", keys = itemKeysParent), measuredItemChildCPC_tree = Dimension(name = "measuredItemChildCPC_tree", keys = itemKeysChild ), timePointYears = Dimension(name = "timePointYears", keys = timeKeys) )) tree = GetData(keyTree) oldtree=subset(tree,Value==0) body=paste("The Email contains a backup of the old tree with zero values", sep='\n') sendMailAttachment(oldtree,"old_tree_backup",body) tree=subset(tree,timePointYears<2014) tempor=dcast(tree, geographicAreaM49 + measuredElementSuaFbs+ measuredItemParentCPC_tree + measuredItemChildCPC_tree~ timePointYears, value.var="Value") tree=melt(tempor,id.vars = 1:4) colnames(tree)[colnames(tree)=="variable"] <- "timePointYears" colnames(tree)[colnames(tree)=="value"] <- "Value" tree=subset(tree,Value==0) countryKeysOld=GetCodeList(domain = "FAOStat1", dataset = "updated_sua_2013_data",dimension="geographicAreaFS")[,code] elemKeysOld=GetCodeList(domain = "FAOStat1", dataset = "updated_sua_2013_data",dimension="measuredElementFS")[,code] itemKeysOld=GetCodeList(domain = "FAOStat1", dataset = "updated_sua_2013_data",dimension="measuredItemFS")[,code] timeKeysOld=as.character(c(2000:2013)) countryKeysOld=countrymapping$fal[countrymapping$m49==areaKeys] keyOld = DatasetKey(domain = "FAOStat1", dataset = "updated_sua_2013_data", dimensions = list( geographicAreaFS = Dimension(name = "geographicAreaFS", keys =countryKeysOld), measuredElementFS = Dimension(name = "measuredElementFS", keys = "41"), measuredItemFS = Dimension(name = "measuredItemFS", keys = itemKeysOld), timePointYears = Dimension(name = "timePointYears", keys = timeKeysOld) )) sua2013= GetData(keyOld) sua2013[,measuredItemFS:=str_pad(measuredItemFS,4,side="left", pad="0")] sua2013[,measuredItemSuaFbs:=fcl2cpc(measuredItemFS)] #sua2013=subset(sua2013,measuredItemSuaFbs) #%in% tree$measuredItemChildCPC_tree #sua2013=subset(sua2013,measuredItemSuaFbs ) #%in% processedCPC tempor=dcast(sua2013, geographicAreaFS + measuredElementFS+ measuredItemSuaFbs ~ timePointYears, value.var="Value", fun.aggregate = sum) sua2013=melt(tempor,id.vars = 1:3) colnames(sua2013)[colnames(sua2013)=="variable"] <- "timePointYears" colnames(sua2013)[colnames(sua2013)=="value"] <- "oldEr" alltree=merge(tree,sua2013,by.x=c("measuredItemChildCPC_tree","timePointYears"),by.y=c("measuredItemSuaFbs","timePointYears"), all.y=T) alltree=data.table(alltree) alltree[,newER:=ifelse(is.na(Value)==T,oldEr,Value)] alltree[,newER:=pmax(Value,oldEr/10000, na.rm=T)] #alltree[,medEr:=median(oldEr/10000), by=c("geographicAreaM49","measuredElementSuaFbs","measuredItemParentCPC_tree", "measuredItemChildCPC_tree")] newtree=alltree[,c(colnames(tree),"newER"),with=F] newtree=subset(newtree,is.na(geographicAreaM49)==F) newtree=nameData(domain="suafbs", dataset="ess_fbs_commodity_tree2",newtree) body=paste("The Email contains a list of extraction rates that have been modified taking into account old 41 element from Faostat1.", "Column Value reports the old value, newER the new one.", sep='\n') sendMailAttachment(newtree,"Changed_extraction_rates",body) newtree2=copy(newtree) newtree2=newtree2[,Value:=newER] newtree2=newtree2[,newER:=NULL] newtreewide=dcast(newtree2, geographicAreaM49 + measuredElementSuaFbs+ measuredItemParentCPC_tree + measuredItemChildCPC_tree ~ timePointYears, value.var="Value") newtreewide=data.table(newtreewide) newtreewide[!(geographicAreaM49 %in% top48FBSCountries),`2014`:=`2013`] newtreewide[!(geographicAreaM49 %in% top48FBSCountries),`2015`:=`2013`] newtreewide[!(geographicAreaM49 %in% top48FBSCountries),`2016`:=`2013`] newtree2=melt(newtreewide,id.vars = 1:4, measure.vars = 5:21) newtree2=data.table(newtree2) colnames(newtree2)[colnames(newtree2)=="variable"] <- "timePointYears" colnames(newtree2)[colnames(newtree2)=="value"] <- "Value" newtree2[,timePointYears:=as.character(timePointYears)] newtree2[,flagObservationStatus:="E"] newtree2[,flagMethod:="f"] newtree2=subset(newtree2,is.na(Value)==F) newtree_named=nameData(domain="suafbs", dataset="ess_fbs_commodity_tree2",newtree2) SaveData(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", newtree2, waitMode = "wait", waitTimeout = 600000, chunkSize = 50000) <file_sep>/modules/SUA_bal_compilation_round2021/Shares_tree_corrections.R library(faosws) library(faoswsUtil) library(faoswsBalancing) library(faoswsStandardization) library(dplyr) library(data.table) library(tidyr) library(openxlsx) # The only parameter is the string to print # COUNTRY is taken from environment (parameter) dbg_print <- function(x) { message(paste0("NEWBAL (", COUNTRY, "): ", x)) } start_time <- Sys.time() R_SWS_SHARE_PATH <- Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { R_SWS_SHARE_PATH <- "//hqlprsws1.hq.un.fao.org/sws_r_share" mydir <- "modules/SUA_bal_compilation_round2021" SETTINGS <- faoswsModules::ReadSettings(file.path(mydir, "sws.yml")) SetClientFiles(SETTINGS[["certdir"]]) GetTestEnvironment(baseUrl = SETTINGS[["server"]], token = SETTINGS[["token"]]) } COUNTRY <- as.character(swsContext.datasets[[1]]@dimensions$geographicAreaM49@keys) COUNTRY_NAME <- nameData( "suafbs", "sua_unbalanced", data.table(geographicAreaM49 = COUNTRY))$geographicAreaM49_description dbg_print("parameters") USER <- regmatches( swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE) ) #if (!file.exists(file.path(R_SWS_SHARE_PATH, USER))) { # dir.create(file.path(R_SWS_SHARE_PATH, USER)) #} startYear <- as.numeric(swsContext.computationParams$startYear) #startYear <- 2014 endYear <- as.numeric(swsContext.computationParams$endYear) #endYear<- 2019 # 2000 rimane hard coded , 2019 in YEARS diventa endYear da input utente YEARS <- as.character(2000:endYear) #rimane hard coded coeff_stock_year <- 2013 #diventa funzione dell ' input utente il reference year 2009:2013 reference_years <- (startYear-5):(startYear-1) #focus interval è il principale input del'utente 2014-2019 focus_interval <- startYear:endYear #NOTES for future complete parametrization. Where opening stock 2014 table is took in consideration, 2014 year is hard coded Item_Parent <- as.character(swsContext.computationParams$Item_Parent) #Item_Parent <- "02211" # Always source files in R/ (useful for local runs). # Your WD should be in faoswsStandardization/ sapply(dir("R", full.names = TRUE), source) p <- defaultStandardizationParameters() p$itemVar <- "measuredItemSuaFbs" p$mergeKey[p$mergeKey == "measuredItemCPC"] <- "measuredItemSuaFbs" p$elementVar <- "measuredElementSuaFbs" p$childVar <- "measuredItemChildCPC" p$parentVar <- "measuredItemParentCPC" p$createIntermetiateFile <- "TRUE" p$protected <- "Protected" p$official <- "Official" #to be corrected shareDownUp_file <- file.path(R_SWS_SHARE_PATH, USER, paste0("shareDownUp_", COUNTRY, ".csv")) tourist_cons_table <- ReadDatatable("keep_tourist_consumption") stopifnot(nrow(tourist_cons_table) > 0) TourismNoIndustrial <- tourist_cons_table[small == "X"]$tourist dbg_print("define functions") ######### FUNCTIONS: at some point, they will be moved out of this file. #### # Replacement for merge(x, y, by = VARS, all.x = TRUE) that do not set keys # By default it behaves as dplyr::left_join(). If nomatch = 0, non-matching # rows will not be returned dt_left_join <- function(x, y, by = NA, allow.cartesian = FALSE, nomatch = NA) { if (anyNA(by)) { stop("'by' is required") } if (any(!is.data.table(x), !is.data.table(y))) { stop("'x' and 'y' should be data.tables") } res <- y[x, on = by, allow.cartesian = allow.cartesian, nomatch = nomatch] setcolorder(res, c(names(x), setdiff(names(y), names(x)))) res } dt_full_join <- function(x, y, by = NA) { if (anyNA(by)) { stop("'by' is required") } if (any(!is.data.table(x), !is.data.table(y))) { stop("'x' and 'y' should be data.tables") } res <- merge(x, y, by = by, all = TRUE) # merge sets the key to `by` setkey(res, NULL) res } coeffs_stocks_mod <- function(x) { tmp <- lm(data = x[timePointYears <= coeff_stock_year], supply_inc ~ supply_exc + trend) as.list(tmp$coefficients) } # This function will recalculate opening stocks from the first # observation. Always. update_opening_stocks <- function(x) { x <- x[order(geographicAreaM49, measuredItemSuaFbs, timePointYears)] groups <- unique(x[, c("geographicAreaM49", "measuredItemSuaFbs"), with = FALSE]) res <- list() for (i in seq_len(nrow(groups))) { z <- x[groups[i], on = c("geographicAreaM49", "measuredItemSuaFbs")] if (nrow(z) > 1) { for (j in seq_len(nrow(z))[-1]) { # negative delta cannot be more than opening if (z$delta[j-1] < 0 & abs(z$delta[j-1]) > z$new_opening[j-1]) { z$delta[j-1] <- - z$new_opening[j-1] } z$new_opening[j] <- z$new_opening[j-1] + z$delta[j-1] } # negative delta cannot be more than opening if (z$delta[j] < 0 & abs(z$delta[j]) > z$new_opening[j]) { z$delta[j] <- - z$new_opening[j] } } res[[i]] <- z } rbindlist(res) } #send email function send_mail <- function(from = NA, to = NA, subject = NA, body = NA, remove = FALSE) { if (missing(from)) from <- '<EMAIL>' if (missing(to)) { if (exists('swsContext.userEmail')) { to <- swsContext.userEmail } } if (is.null(to)) { stop('No valid email in `to` parameter.') } if (missing(subject)) stop('Missing `subject`.') if (missing(body)) stop('Missing `body`.') if (length(body) > 1) { body <- sapply( body, function(x) { if (file.exists(x)) { # https://en.wikipedia.org/wiki/Media_type file_type <- switch( tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), txt = 'text/plain', csv = 'text/csv', png = 'image/png', jpeg = 'image/jpeg', jpg = 'image/jpeg', gif = 'image/gif', xls = 'application/vnd.ms-excel', xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', doc = 'application/msword', docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf = 'application/pdf', zip = 'application/zip', # https://stackoverflow.com/questions/24725593/mime-type-for-serialized-r-objects rds = 'application/octet-stream' ) if (is.null(file_type)) { stop(paste(tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), 'is not a supported file type.')) } else { res <- sendmailR:::.file_attachment(x, basename(x), type = file_type) if (remove == TRUE) { unlink(x) } return(res) } } else { return(x) } } ) } else if (!is.character(body)) { stop('`body` should be either a string or a list.') } sendmailR::sendmail(from, to, subject, as.list(body)) } # Fill NAs by LOCF/FOCB/interpolation if more than two # non-missing observations are available, otherwhise just # replicate the only non-missing observation na.fill_ <- function(x) { if(sum(!is.na(x)) > 1) { zoo::na.fill(x, "extend") } else { rep(x[!is.na(x)], length(x)) } } `%!in%` <- Negate(`%in%`) # RemainingToProcessedParent() and RemainingProdChildToAssign() will # be used in the derivation of shareDownUp RemainingToProcessedParent <- function(data) { data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] data[, only_child_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(production_of_child) & !is.na(parent_qty_processed) & production_of_child > 0, by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[ only_child_left == TRUE, processed_to_child := remaining_processed_parent * extractionRate ] data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] return(data) } RemainingProdChildToAssign <- function(data) { data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] data[, only_parent_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(parent_qty_processed) & parent_qty_processed >= 0 ] data[only_parent_left==TRUE,processed_to_child:=ifelse(only_parent_left==TRUE,remaining_to_process_child,processed_to_child)] data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] return(data) } # The fmax function is used when fixing the processingShare of coproducts. # If TRUE it means that "+" or "or" cases are involved. fmax <- function(child, main, share, plusor = FALSE) { main <- unique(main) if (plusor) { found <- sum(sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)) if (found == 0) { return(max(share, na.rm = TRUE)) } else if (found == 1) { return( share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]] ) } else { # should be 2 return(max(share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]], na.rm = TRUE)) } } else { if (sum(grepl(main, child)) > 0) { share[child == main] } else { max(share, na.rm = TRUE) } } } # Function that calculates imbalance as supply - utilizations (both calculated # inside the function, dropped if keep_(supply|utilizations) set to FALSE). # rollavg() is a rolling average function that uses computed averages # to generate new values if there are missing values (and FOCB/LOCF). # I.e.: # vec <- c(NA, 2, 3, 2.5, 4, 3, NA, NA, NA) # #> RcppRoll::roll_mean(myvec, 3, fill = 'extend', align = 'right') #[1] NA NA NA 2.500000 3.166667 3.166667 NA NA NA # #> rollavg(myvec) #[1] 2.000000 2.000000 3.000000 2.500000 4.000000 3.000000 3.166667 3.388889 3.185185 rollavg <- function(x, order = 3) { # order should be > 2 stopifnot(order >= 3) non_missing <- sum(!is.na(x)) # For cases that have just two non-missing observations order <- ifelse(order > 2 & non_missing == 2, 2, order) if (non_missing == 1) { x[is.na(x)] <- na.omit(x)[1] } else if (non_missing >= order) { n <- 1 while(any(is.na(x)) & n <= 10) { # 10 is max tries movav <- suppressWarnings(RcppRoll::roll_mean(x, order, fill = 'extend', align = 'right')) movav <- data.table::shift(movav) x[is.na(x)] <- movav[is.na(x)] n <- n + 1 } x <- zoo::na.fill(x, 'extend') } return(x) } ############################## / FUNCTIONS ################################## dbg_print("end functions") ##################################### TREE ################################# dbg_print("download tree") #tree <- getCommodityTreeNewMethod(COUNTRY, YEARS) #years range took with suerior margin with eccess (to not define years in back compilation) tree <- getCommodityTreeNewMethod(COUNTRY,as.character(2000:2030)) stopifnot(nrow(tree) > 0) tree <- tree[geographicAreaM49 %chin% COUNTRY] # The `tree_exceptions` will npo be checked by validateTree() # Exception: high share conmfirmed by official data tree_exceptions <- tree[geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01"] if (nrow(tree_exceptions) > 0) { tree <- tree[!(geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01")] } validateTree(tree) if (nrow(tree_exceptions) > 0) { tree <- rbind(tree, tree_exceptions) rm(tree_exceptions) } ## NA ExtractionRates are recorded in the sws dataset as 0 ## for the standardization, we nee them to be treated as NA ## therefore here we are re-changing it # TODO: Keep all protected 0 ERs tree[Value == 0 & !(flagObservationStatus == "E" & flagMethod == "f"), Value := NA] #proc_level_exceptions <- ReadDatatable("processing_level_exceptions") # #if (nrow(proc_level_exceptions) > 0) { # setnames(proc_level_exceptions, c("m49_code", "parent", "child"), # c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC")) # # tree <- # tree[!proc_level_exceptions[is.na(level)], # on = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC")] # # proc_level_exceptions <- proc_level_exceptions[!is.na(level)] #} tree_to_send <- tree[is.na(Value) & measuredElementSuaFbs=="extractionRate"] FILL_EXTRACTION_RATES = TRUE if (FILL_EXTRACTION_RATES == TRUE) { expanded_tree <- merge( data.table( geographicAreaM49 = unique(tree$geographicAreaM49), timePointYears = as.character(sort(2000:(max(tree[, timePointYears])))) ), unique( tree[, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC"), with = FALSE ] ), by = "geographicAreaM49", all = TRUE, allow.cartesian = TRUE ) tree <- tree[expanded_tree, on = colnames(expanded_tree)] # flags for carry forward/backward tree[is.na(Value), c("flagObservationStatus", "flagMethod") := list("E", "t")] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = -Inf ] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = Inf ] # keep orig flags tree[, flagObservationStatus := i.i.flagObservationStatus] tree[, flagMethod := i.i.flagMethod] tree[, names(tree)[grep("^i\\.", names(tree))] := NULL] } # XXX: connections removed here that should not exist in # the commodity tree (so, they should be fixed there) tree[ #timePointYears >= 2014 & ((measuredItemParentCPC == "02211" & measuredItemChildCPC == "22212") | #cheese from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22251.01")), `:=`( Value = NA, flagObservationStatus = "M", flagMethod = "n" ) ] #correction of milk tree for Czechia TO DO: generalize for the next round tree[ #timePointYears >= 2014 & geographicAreaM49=="203" & #“whole milk powder” from whole cow milk cannot come from skim mulk of cow ((measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22211") | #“whole milk condensed” from whole cow milk cannot come from skim mulk of cow (measuredItemParentCPC == "22110.02" & measuredItemChildCPC == "22222.01")), `:=`( Value = NA, flagObservationStatus = "M", flagMethod = "n" ) ] # saveRDS( # tree[ # !is.na(Value) & measuredElementSuaFbs == "extractionRate", # -grepl("measuredElementSuaFbs", names(tree)), # with = FALSE # ], # file.path(R_SWS_SHARE_PATH, "FBSvalidation", COUNTRY, "tree.rds") # ) tree_to_send <- tree_to_send %>% dplyr::anti_join( tree[is.na(Value) & measuredElementSuaFbs == "extractionRate"], by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod") ) %>% dplyr::select(-Value) %>% dplyr::left_join( tree, by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "flagObservationStatus", "flagMethod") ) %>% setDT() tree_to_send <- tree_to_send[, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] setnames( tree_to_send, c("measuredItemParentCPC", "measuredItemChildCPC"), c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree") ) tree_to_send <- nameData("suafbs", "ess_fbs_commodity_tree2", tree_to_send, except = c('measuredElementSuaFbs', 'timePointYears')) tree_to_send[, `:=`( measuredItemParentCPC_tree = paste0("'", measuredItemParentCPC_tree), measuredItemChildCPC_tree = paste0("'", measuredItemChildCPC_tree)) ] #tmp_file_extr <- file.path(TMP_DIR, paste0("FILLED_ER_", COUNTRY, ".csv")) #write.csv(tree_to_send, tmp_file_extr) # XXX remove NAs tree <- tree[!is.na(Value)] uniqueLevels <- unique(tree[, c("geographicAreaM49", "timePointYears"), with = FALSE]) levels <- list() treeLevels <- list() for (i in seq_len(nrow(uniqueLevels))) { filter <- uniqueLevels[i, ] treeCurrent <- tree[filter, on = c("geographicAreaM49", "timePointYears")] levels <- findProcessingLevel(treeCurrent, "measuredItemParentCPC", "measuredItemChildCPC") setnames(levels, "temp", "measuredItemParentCPC") treeLevels[[i]] <- dt_left_join(treeCurrent, levels, by = "measuredItemParentCPC") } tree <- rbindlist(treeLevels) tree[, processingLevel := max(processingLevel, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredElementSuaFbs", "measuredItemChildCPC") ] # XXX Check if this one is still good or it can be obtained within the dataset processed_item_datatable <- ReadDatatable("processed_item") processedCPC <- processed_item_datatable[, measured_item_cpc] # XXX what is this for? itemMap <- GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemMap <- itemMap[, .(measuredItemSuaFbs = code, type)] ##################################### / TREE ################################ ############################ POPULATION ##################################### ############################ / POPULATION ################################## ############################################################### DATA ####### # 5510 Production[t] # 5610 Import Quantity [t] # 5071 Stock Variation [t] # 5023 Export Quantity [t] # 5910 Loss [t] # 5016 Industrial uses [t] # 5165 Feed [t] # 5520 Seed [t] # 5525 Tourist Consumption [t] # 5164 Residual other uses [t] # 5141 Food [t] # 664 Food Supply (/capita/day) [Kcal] elemKeys <- c("5510", "5610", "5071", "5113", "5023", "5910", "5016", "5165", "5520", "5525", "5164", "5166", "5141") itemKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys <- itemKeys$code # NOTE: the definition of "food_resid" changed (see inside newBalancing) # (so, the tables below are not used anymore) #food_classification_country_specific <- # ReadDatatable("food_classification_country_specific", # where = paste0("geographic_area_m49 IN ('", COUNTRY, "')")) # #food_classification_country_specific <- # food_classification_country_specific[geographic_area_m49 == COUNTRY] # #food_only_items <- food_classification_country_specific[food_classification == 'Food Residual', measured_item_cpc] Utilization_Table <- ReadDatatable("utilization_table_2018") stockable_items <- Utilization_Table[stock == 'X', cpc_code] zeroWeight <- ReadDatatable("zero_weight")[, item_code] flagValidTable <- ReadDatatable("valid_flags") # We decided to unprotect E,e (replaced outliers). Done after they are # replaced (i.e., if initially an Ee exists, it should remain; they need # to be unprotected for balancing. flagValidTable[flagObservationStatus == 'E' & flagMethod == 'e', Protected := FALSE] # XXX: we need to unprotect I,c because it was being assigned # to imputation of production of derived which is NOT protected. # This will need to change in the next exercise. flagValidTable[flagObservationStatus == 'I' & flagMethod == 'c', Protected := FALSE] # Nutrients are: # 1001 Calories # 1003 Proteins # 1005 Fats if (CheckDebug()) { key <- DatasetKey( domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = YEARS) ) ) } else { key <- swsContext.datasets[[2]] key@dimensions$timePointYears@keys <- YEARS key@dimensions$measuredItemFbsSua@keys <- itemKeys key@dimensions$measuredElementSuaFbs@keys <- elemKeys key@dimensions$geographicAreaM49@keys <- COUNTRY } dbg_print("download data") # LOAD data <- GetData(key) #if (unique(data[, geographicAreaM49]) != COUNTRY) { stop("Invalid Unbalance dataset")} # Remove item that is not par of agriculture domain data <- data[measuredItemFbsSua != "F1223"] if (Item_Parent %!in% unique(data[, measuredItemFbsSua]) & Item_Parent %!in% unique(tree[, measuredItemParentCPC])) { #print(paste0("Not valid Parent Item code")) send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Not valid Parent Item code", body = c(paste("The parent item inserted is not correct")) ) stop("Not valid Parent Item code") } dbg_print("convert sugar") ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## data <- convertSugarCodes_new(data) #################### FODDER CROPS ########################################## # TODO: create SWS datatable for this. # Some of these items may be missing in reference files, # thus we carry forward the last observation. fodder_crops_items <- tibble::tribble( ~description, ~code, "Maize for forage", "01911", "Alfalfa for forage", "01912", "Sorghum for forage", "01919.01", "Rye grass for forage", "01919.02", "Other grasses for forage", "01919.91", "Clover for forage", "01919.03", "Other oilseeds for forage", "01919.94", "Other legumes for forage", "01919.92", "Cabbage for fodder", "01919.04", "Mixed grass and legumes for forage", "01919.93", "Turnips for fodder", "01919.05", "Beets for fodder", "01919.06", "Carrots for fodder", "01919.07", "Swedes for fodder", "01919.08", "Other forage products, nes", "01919.96", "Other forage crops, nes", "01919.95", "Hay for forage, from legumes", "01919.10", "Hay for forage, from grasses", "01919.09", "Hay for forage, from other crops nes", "01919.11" ) fodder_crops_availab <- data[ measuredItemFbsSua %chin% fodder_crops_items$code & measuredElementSuaFbs == "5510" ] if (nrow(fodder_crops_availab) > 0) { fodder_crops_complete <- CJ( geographicAreaM49 = unique(fodder_crops_availab$geographicAreaM49), measuredElementSuaFbs = "5510", timePointYears = unique(data$timePointYears), measuredItemFbsSua = unique(fodder_crops_availab$measuredItemFbsSua) ) fodder_crops_complete <- fodder_crops_complete[order(geographicAreaM49, measuredItemFbsSua, timePointYears)] fodder_crops <- dt_left_join( fodder_crops_complete, fodder_crops_availab[, .(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)], by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears") ) fodder_crops[, Value := zoo::na.locf(Value), by = c("geographicAreaM49", "measuredItemFbsSua") ] fodder_crops_new <- fodder_crops[ !fodder_crops_availab, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears") ] if (nrow(fodder_crops_new) > 0) { fodder_crops_new[, `:=`(flagObservationStatus = "E", flagMethod = "t")] data <- rbind(data, fodder_crops_new) } } #################### / FODDER CROPS ######################################## opening_stocks_2014 <- ReadDatatable( "opening_stocks_2014", where = paste0("m49_code IN (", paste(shQuote(COUNTRY, type = "sh"), collapse = ", "), ")") ) # The procedure works even if no previous opening stocks exists, but in that # case there is no way to know if data does not exist because there was an # issue downloading data or because it actually does not exist. Luckily there # are many calls to SWS, which should fail if there are issues: it is unlikely # that only this one fails. #stopifnot(nrow(opening_stocks_2014) > 0) non_null_prev_deltas <- unique( data[ measuredElementSuaFbs == "5071" & timePointYears %in% reference_years ][, .SD[sum(!dplyr::near(Value, 0)) > 0], by = c("geographicAreaM49", "measuredItemFbsSua") ][, .(geographicAreaM49, measuredItemFbsSua) ] ) opening_stocks_2014[opening_stocks < 0, opening_stocks := 0] opening_stocks_2014 <- opening_stocks_2014[ m49_code %in% COUNTRY, .( geographicAreaM49 = m49_code, measuredItemFbsSua = cpc_code, timePointYears = "2014", Value_cumulated = opening_stocks ) ] # Keep only those for which recent variations are available opening_stocks_2014 <- opening_stocks_2014[ non_null_prev_deltas, on = c("geographicAreaM49", "measuredItemFbsSua"), nomatch = 0 ] original_opening_stocks <- data[measuredElementSuaFbs == "5113"] original_opening_stocks <- flagValidTable[ original_opening_stocks, on = c("flagObservationStatus", "flagMethod") ][, Valid := NULL ] # Remove protected in 2014 from cumulated opening_stocks_2014 <- opening_stocks_2014[ !original_opening_stocks[ timePointYears == "2014" & Protected == TRUE, .(geographicAreaM49, measuredItemFbsSua) ], on = c("geographicAreaM49", "measuredItemFbsSua") ] all_opening_stocks <- merge( original_opening_stocks, opening_stocks_2014, by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), all = TRUE ) all_opening_stocks[ !Protected %in% TRUE & is.na(Value) & !is.na(Value_cumulated), `:=`( Value = Value_cumulated, flagObservationStatus = "I", flagMethod = "-", # We protect these, in any case, because they should not # be overwritten, even if not (semi) official or expert Protected = TRUE, measuredElementSuaFbs = "5113", timePointYears = "2014" ) ][, Value_cumulated := NULL ] # Now, for all remaining stockable items, we create opening # stocks in 2014 as 20% of supply in 2013 remaining_opening_stocks <- data[ timePointYears == "2013" & measuredItemFbsSua %chin% setdiff( stockable_items, all_opening_stocks$measuredItemFbsSua ) ][, .( opening_20 = sum( Value[measuredElementSuaFbs %chin% c("5510", "5610")], - Value[measuredElementSuaFbs == "5910"], na.rm = TRUE ) * 0.2, timePointYears = "2014" ), by = c("geographicAreaM49", "measuredItemFbsSua") ] remaining_opening_stocks[opening_20 < 0, opening_20 := 0] all_opening_stocks <- merge( all_opening_stocks, remaining_opening_stocks, by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), all = TRUE ) all_opening_stocks <- all_opening_stocks[!is.na(timePointYears)] all_opening_stocks[ !Protected %in% TRUE & is.na(Value) & !is.na(opening_20), `:=`( Value = opening_20, flagObservationStatus = "I", flagMethod = "i", # We protect these, in any case, because they should not # be overwritten, even if not (semi) official or expert Protected = TRUE ) ][, opening_20 := NULL ] complete_all_opening <- CJ( geographicAreaM49 = unique(all_opening_stocks$geographicAreaM49), timePointYears = as.character(min(all_opening_stocks$timePointYears):as.numeric(tail(YEARS,1))), measuredItemFbsSua = unique(all_opening_stocks$measuredItemFbsSua) ) all_opening_stocks <- merge( complete_all_opening, all_opening_stocks, by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), all = TRUE ) all_opening_stocks[, orig_val := Value] all_opening_stocks <- all_opening_stocks[!is.na(Value)][ all_opening_stocks, on = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears"), roll = Inf] all_opening_stocks[ is.na(orig_val) & !is.na(Value), `:=`( Protected = FALSE, flagObservationStatus = "E", flagMethod = "t" ) ] all_opening_stocks[, measuredElementSuaFbs := "5113"] all_opening_stocks[, orig_val := NULL] all_opening_stocks[, names(all_opening_stocks)[grep("^i\\.", names(all_opening_stocks))] := NULL] all_opening_stocks <- all_opening_stocks[!is.na(timePointYears)] # Generate stocks variations for items for which opening # exists for ALL years and variations don't exist opening_avail_all_years <- all_opening_stocks[ !is.na(Value) & timePointYears >= focus_interval[1], .SD[.N == (tail(focus_interval,1) - focus_interval[1] + 1)], measuredItemFbsSua ] delta_avail_for_open_all_years <- data[ measuredElementSuaFbs == "5071" & timePointYears >= focus_interval[1] & measuredItemFbsSua %chin% opening_avail_all_years$measuredItemFbsSua, .SD[.N == (tail(focus_interval,1) - focus_interval[1] + 1)], measuredItemFbsSua ] to_generate_by_ident <- setdiff( opening_avail_all_years$measuredItemFbsSua, delta_avail_for_open_all_years$measuredItemFbsSua ) data_rm_ident <- data[measuredElementSuaFbs == "5071" & measuredItemFbsSua %chin% to_generate_by_ident] if (length(to_generate_by_ident) > 0) { opening_avail_all_years <- opening_avail_all_years[measuredItemFbsSua %chin% to_generate_by_ident] opening_avail_all_years[, Protected := NULL] next_opening_key <- DatasetKey( domain = "Stock", dataset = "stocksdata", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = "5113"), measuredItemFbsSua = Dimension(name = "measuredItemCPC", keys = unique(opening_avail_all_years$measuredItemFbsSua)), timePointYears = Dimension(name = "timePointYears", keys = as.character(as.numeric(max(opening_avail_all_years$timePointYears)) + 1)) ) ) next_opening <- GetData(next_opening_key) setnames( next_opening, c("measuredItemCPC", "measuredElement"), c("measuredItemFbsSua", "measuredElementSuaFbs") ) opening_avail_all_years <- rbind(opening_avail_all_years, next_opening) opening_avail_all_years <- opening_avail_all_years[ order(geographicAreaM49, measuredItemFbsSua, timePointYears) ] opening_avail_all_years[, delta := shift(Value, type = "lead") - Value, by = c("geographicAreaM49", "measuredItemFbsSua") ] opening_avail_all_years[, delta := ifelse( timePointYears == max(timePointYears) & is.na(delta), 0, delta ), by = c("geographicAreaM49", "measuredItemFbsSua") ] opening_avail_all_years <- dt_left_join( opening_avail_all_years, flagValidTable, by = c("flagObservationStatus", "flagMethod") ) opening_avail_all_years[shift(Protected, type = "lead") == TRUE & Protected == TRUE, `:=`(delta_flag_obs = "T", delta_flag_method = "p")] opening_avail_all_years[!(shift(Protected, type = "lead") == TRUE & Protected == TRUE), `:=`(delta_flag_obs = "I", delta_flag_method = "i")] delta_identity <- opening_avail_all_years[ timePointYears %in% focus_interval[1]:tail(focus_interval,1), .( geographicAreaM49, measuredItemFbsSua, timePointYears, measuredElementSuaFbs = "5071", Value = delta, flagObservationStatus = delta_flag_obs, flagMethod = delta_flag_method ) ] delta_identity <- delta_identity[!data_rm_ident, on = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears")] data <- rbind(data, delta_identity) data <- data[order(geographicAreaM49, measuredItemFbsSua, timePointYears, measuredElementSuaFbs)] } # / Generate stocks variations for items for which opening # / exists for ALL years and variations don't exist # Recalculate opening stocks data_for_opening <- dt_left_join( all_opening_stocks[, .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, new_opening = Value) ], data[ measuredElementSuaFbs == '5071' & timePointYears %in% focus_interval[1]:tail(focus_interval,1) & !is.na(Value), .(geographicAreaM49, measuredItemSuaFbs = measuredItemFbsSua, timePointYears, delta = Value) ], by = c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears") ) data_for_opening[is.na(delta), delta := 0] data_for_opening <- data_for_opening[timePointYears >= focus_interval[1]] data_for_opening <- update_opening_stocks(data_for_opening) all_opening_stocks <- dt_left_join( all_opening_stocks, data_for_opening[, .( geographicAreaM49, measuredItemFbsSua = measuredItemSuaFbs, timePointYears, new_opening ) ], by = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") ) all_opening_stocks[ !is.na(new_opening) & (round(new_opening) != round(Value) | is.na(Value)), `:=`( Value = new_opening, flagObservationStatus = "E", flagMethod = "u", Protected = FALSE ) ] all_opening_stocks[, new_opening := NULL] # / Recalculate opening stocks data <- dt_left_join(data, flagValidTable, by = c("flagObservationStatus", "flagMethod")) data[flagObservationStatus %chin% c("", "T"), `:=`(Official = TRUE, Protected = TRUE)] data[is.na(Official), Official := FALSE] data[is.na(Protected), Protected := FALSE] # We remove "5113" (opening stocks) as will be stored in separate table. data <- data[measuredElementSuaFbs != "5113"] dbg_print("elementToCodeNames") # XXX FIXME: the elementCodesToNames below is # not working proberply, see issue #38 codes <- as.data.table(tibble::tribble( ~measuredElementSuaFbs, ~name, "5910", "exports", "5520", "feed", "5141", "food", "5023", "foodManufacturing", "5610", "imports", "5165", "industrial", "5016", "loss", "5510", "production", "5525", "seed", "5164", "tourist", "5071", "stockChange" )) data <- dt_left_join(data, codes, by = "measuredElementSuaFbs") data[, measuredElementSuaFbs := name] data[, name := NULL] # NOTE: if this should be used again (#38), camelCase the element names (#45) #data <- # elementCodesToNames( # data, # itemCol = "measuredItemFbsSua", # elementCol = "measuredElementSuaFbs" # ) # XXX: there are some NAs here, but probably there shouldn't data <- data[!is.na(measuredElementSuaFbs)] setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") ########## Remove feed if new element and negative imbalance is huge # Feed requires country-specific reference files, which are being updated. # Until these get reviewed, the feed module will generate feed items in # some countries, where it is not required/needed/appropriate. Below, we # remove the NEW feed item if the NEGATIVE imbalance obtained by including # it is more than 50% of supply (e.g., -72%). ##### calcuate Imbalance function ##### calculateImbalance <- function(data, supply_add = c("production", "imports"), supply_subtract = c("exports", "stockChange"), supply_all = union(supply_add, supply_subtract), item_name = "measuredItemSuaFbs", bygroup = c("geographicAreaM49", "timePointYears", item_name), keep_supply = TRUE, keep_utilizations = TRUE) { stopifnot(is.data.table(data)) data[, `:=`( supply = sum(Value[measuredElementSuaFbs %chin% supply_add], - Value[measuredElementSuaFbs %chin% supply_subtract], na.rm = TRUE), # All elements that are NOT supply elements utilizations = sum(Value[!(measuredElementSuaFbs %chin% supply_all)], na.rm = TRUE) ), by = bygroup ][, imbalance := supply - utilizations ] if (keep_supply == FALSE) { data[, supply := NULL] } if (keep_utilizations == FALSE) { data[, utilizations := NULL] } } outside <- function(x, lower = NA, upper = NA) { x < lower | x > upper } ####### new_feed <- data[ measuredElementSuaFbs == "feed", .( pre = sum(!is.na(Value[timePointYears <= focus_interval[1]-1])), post = sum(!is.na(Value[timePointYears >= focus_interval[1]])) ), by = c("geographicAreaM49", "measuredItemSuaFbs") ][ pre == 0 & post > 0 ][, c("pre", "post") := NULL ] msg_new_feed_remove <- "No NEW feed removed" msg_new_feed_dubious <- "No other NEW items should be removed" if (nrow(new_feed) > 0) { prev_data_avg <- data[ new_feed, on = c("geographicAreaM49", "measuredItemSuaFbs") ][ timePointYears >= focus_interval[1]-4 & timePointYears <= focus_interval[1]-1 ][ order(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears), Value := na.fill_(Value), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ][, .(Value = sum(Value) / sum(!is.na(Value)), timePointYears = 0), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ] calculateImbalance(prev_data_avg, supply_subtract = c("exports", "stockChange")) prev_processed_avg <- prev_data_avg[ supply > 0 & utilizations > 0 & measuredElementSuaFbs == "foodManufacturing" & !is.na(Value), .(geographicAreaM49, measuredItemSuaFbs, proc_ratio = Value / supply) ] new_data_avg <- data[ new_feed, on = c("geographicAreaM49", "measuredItemSuaFbs") ][ measuredElementSuaFbs != "foodManufacturing" & timePointYears >= focus_interval[1] ][ order(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears), Value := na.fill_(Value), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ][, .(Value = sum(Value) / sum(!is.na(Value) & !dplyr::near(Value, 0)), timePointYears = 1), by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs") ][ !is.nan(Value) ] calculateImbalance( new_data_avg, keep_utilizations = FALSE, supply_subtract = c("exports", "stockChange") ) new_data_supply <- unique( new_data_avg[, c("geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "supply"), with = FALSE ] ) new_data_proc <- dt_left_join( new_data_supply, prev_processed_avg, by = c("geographicAreaM49", "measuredItemSuaFbs"), nomatch = 0 ) new_data_proc <- new_data_proc[ supply > 0, .(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs = "foodManufacturing", Value = supply * proc_ratio, timePointYears = 1) ] new_data_avg[, c("supply", "imbalance") := NULL] new_data_avg <- rbind( new_data_avg, new_data_proc ) calculateImbalance(new_data_avg, supply_subtract = c("exports", "stockChange")) new_feed_to_remove <- unique( new_data_avg[ imbalance / supply <= -0.3, c("geographicAreaM49", "measuredItemSuaFbs"), with = FALSE ] ) new_feed_to_remove[, measuredElementSuaFbs := "feed"] new_feed_to_remove[, remove_feed := TRUE] new_feed_dubious <- unique( new_data_avg[ imbalance / supply > -0.3 & imbalance / supply <= -0.05, .(geographicAreaM49, measuredItemSuaFbs, x = imbalance / supply) ][order(x)][, x := NULL] ) data <- merge( data, new_feed_to_remove, by = c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementSuaFbs"), all.x = TRUE ) feed_to_remove <- data[ remove_feed == TRUE & Protected == FALSE ][, .(geographicAreaM49, measuredItemSuaFbs, measuredElementSuaFbs, timePointYears) ] data[, remove_feed := NULL] data <- data[!feed_to_remove, on = names(feed_to_remove)] if (nrow(feed_to_remove) > 0) { msg_new_feed_remove <- paste(new_feed_to_remove$measuredItemSuaFbs, collapse = ", ") } if (nrow(new_feed_dubious) > 0) { msg_new_feed_dubious <- paste(new_feed_dubious$measuredItemSuaFbs, collapse = ", ") } } ########## / Remove feed if new element and negative imbalance is huge treeRestricted <- tree[, c("measuredItemParentCPC", "measuredItemChildCPC", "processingLevel"), with = FALSE ] treeRestricted <- unique(treeRestricted[order(measuredItemChildCPC)]) primaryInvolved <- faoswsProduction::getPrimary(processedCPC, treeRestricted, p) dbg_print("primary involved descendents") # XXX: check here, 0111 is in results primaryInvolvedDescendents <- getChildren( commodityTree = treeRestricted, parentColname = "measuredItemParentCPC", childColname = "measuredItemChildCPC", topNodes = primaryInvolved ) # stocks need to be generated for those items for # which "opening stocks" are available items_to_generate_stocks <- unique(all_opening_stocks$measuredItemFbsSua) stock <- CJ( measuredItemSuaFbs = items_to_generate_stocks, measuredElementSuaFbs = 'stockChange', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears) ) # rbind with anti_join data <- rbind( data, stock[!data, on = c('measuredItemSuaFbs', 'measuredElementSuaFbs', 'geographicAreaM49', 'timePointYears')], fill = TRUE ) # XXX what is primaryInvolvedDescendents ????????? #deriv <- CJ(measuredItemSuaFbs = primaryInvolvedDescendents, measuredElementSuaFbs = 'production', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears)) deriv <- CJ( measuredItemSuaFbs = unique(tree$measuredItemChildCPC), measuredElementSuaFbs = 'production', geographicAreaM49 = unique(data$geographicAreaM49), timePointYears = unique(data$timePointYears) ) # rbind with anti_join data <- rbind( data, deriv[!data, on = c('measuredItemSuaFbs', 'measuredElementSuaFbs', 'geographicAreaM49', 'timePointYears')], fill = TRUE ) data[is.na(Official), Official := FALSE] data[is.na(Protected), Protected := FALSE] data[, stockable := measuredItemSuaFbs %chin% stockable_items] # XXX: Remove items for which no production, imports or exports exist after 2013. non_existing_for_imputation <- setdiff( data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports') & timePointYears <= focus_interval[1]-1, unique(measuredItemSuaFbs) ], data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports') & timePointYears >= focus_interval[1], unique(measuredItemSuaFbs) ] ) data <- data[!(measuredItemSuaFbs %chin% non_existing_for_imputation)] ############################################### Create derived production ################################### dbg_print("derivation of shareDownUp") ############# ShareDownUp ---------------------------------------- #this table will be used to assign to zeroweight comodities #the processed quantities of their coproduct coproduct_table <- ReadDatatable('zeroweight_coproducts') stopifnot(nrow(coproduct_table) > 0) # Can't do anything if this information if missing, so remove these cases coproduct_table <- coproduct_table[!is.na(branch)] ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ### XXX removing these cases as '22242.01' appears as zero-weight XXXX ### XXX for main product = '22110.04' XXXX ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX coproduct_table <- coproduct_table[branch != '22242.01 + 22110.04'] coproduct_table <- coproduct_table[, .(measured_item_child_cpc, branch)] coproduct_for_sharedownup <- copy(coproduct_table) coproduct_for_sharedownup_easy <- coproduct_for_sharedownup[!grepl('\\+|or', branch)] coproduct_for_sharedownup_plus <- coproduct_for_sharedownup[grepl('\\+', branch)] coproduct_for_sharedownup_plus <- rbind( tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_plus <- unique(coproduct_for_sharedownup_plus) coproduct_for_sharedownup_or <- coproduct_for_sharedownup[grepl('or', branch)] coproduct_for_sharedownup_or <- rbind( #coproduct_table_or, tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_or <- unique(coproduct_for_sharedownup_or) coproduct_for_sharedownup <- rbind( coproduct_for_sharedownup_easy, coproduct_for_sharedownup_plus, coproduct_for_sharedownup_or ) #Using the whole tree not by level ExtrRate <- tree[ !is.na(Value) & measuredElementSuaFbs == 'extractionRate' ][, .( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value, processingLevel ) ] # We include utilizations to identify if proceseed if the only utilization data_tree <- data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange', 'foodManufacturing', 'loss', 'food', 'industrial', 'feed', 'seed') ] #subset the tree accordingly to parents and child present in the SUA data ExtrRate <- ExtrRate[ measuredItemChildCPC %chin% data_tree$measuredItemSuaFbs & measuredItemParentCPC %chin% data_tree$measuredItemSuaFbs ] setnames(data_tree, "measuredItemSuaFbs", "measuredItemParentCPC") dataProcessingShare<-copy(data_tree) data_tree <- merge( data_tree, ExtrRate, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE, all.y = TRUE ) data_tree <- as.data.table(data_tree) # the availability for parent that have one child and only processed as utilization will # be entirely assigned to processed for that its unique child even for 2014 onwards data_tree[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ] # used to chack if a parent has processed as utilization data_tree[, proc_Median := median( Value[measuredElementSuaFbs == "foodManufacturing" & timePointYears %in% as.numeric(YEARS)], na.rm=TRUE ), by = c(p$parentVar, p$geoVar) ] # boolean variable taking TRUE if the parent has only processed as utilization data_tree[, unique_proc := proc_Median > 0 & !is.na(proc_Median) & # ... is the only utilization all(is.na(Value[!(measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange','foodManufacturing'))])), by = c(p$parentVar, p$geoVar, p$yearVar) ] sel_vars <- c("measuredItemParentCPC", "geographicAreaM49", "timePointYears", "measuredElementSuaFbs", "flagObservationStatus", "flagMethod", "Value", "Official", "measuredItemChildCPC", "extractionRate", "processingLevel") data_tree<- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) # dataset to calculate the number of parent of each child and the number of children of each parent # including zeroweight commodities sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC","timePointYears") data_count <- unique(data_tree[, sel_vars, with = FALSE], by = sel_vars) #Caculate the number of parent of each child data_count[, number_of_parent := .N, by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # calculate the number of children of each parent # we exclude zeroweight to avoid doublecounting of children (processing) data_count[measuredItemChildCPC %!in% zeroWeight, number_of_children := uniqueN(measuredItemChildCPC), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree <- dt_left_join( data_tree, data_count, by = c(p$parentVar, p$childVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) # dataset containing the processed quantity of parents food_proc <- unique( data_tree[ measuredElementSuaFbs == "foodManufacturing", c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value"), with = FALSE ], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value") ) setnames(food_proc, "Value", "parent_qty_processed") # avoid recaculation of shareDownUp from 2014 onwards food_proc[timePointYears > focus_interval[1]-1, parent_qty_processed := NA_real_] data_tree <- dt_left_join( data_tree, food_proc, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "extractionRate", "parent_qty_processed", "processingLevel", "number_of_parent", "number_of_children") data_tree <- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) # dataset containing the production of child commodities dataprodchild <- data[measuredElementSuaFbs %chin% c('production')] setnames(dataprodchild, "measuredItemSuaFbs", "measuredItemChildCPC") dataprodchild <- unique( dataprodchild[, c("geographicAreaM49", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] ) setnames(dataprodchild, "Value", "production_of_child") # to avoid resestimation based on estimated data (processed and production of child) from 2014 onwards dataprodchild[timePointYears > focus_interval[1]-1, production_of_child := NA_real_] data_tree <- dt_left_join( data_tree, dataprodchild, by = c(p$geoVar, p$childVar, p$yearVar) ) # ShareDownups for zeroweights are calculated separately # to avoid double counting when agregating processed quantities of parent # dataset containing informations of zeroweight commodities data_zeroweight <- data_tree[measuredItemChildCPC %chin% zeroWeight] # import data for coproduct relation zw_coproduct <- coproduct_for_sharedownup[, .(zeroweight = measured_item_child_cpc, measuredItemChildCPC = branch) ] zw_coproduct <- unique(zw_coproduct, by = c("measuredItemChildCPC", "zeroweight")) # We subset the zeroweight coproduct reference table by taking only zeroweights and their coproduct # that are childcommodities in the tree of the country zw_coproduct <- zw_coproduct[ measuredItemChildCPC %chin% data_tree$measuredItemChildCPC & zeroweight %chin% data_tree$measuredItemChildCPC ] # Computing information for non zeroweight commodities data_tree <- data_tree[measuredItemChildCPC %!in% zeroWeight] # this dataset will be used when creating processing share and shareUpdown dataComplete <- copy(data_tree) # Quantity of parent destined to the production of the given child (only for child with one parent for the moment) data_tree[, processed_to_child := ifelse(number_of_parent == 1, production_of_child, NA_real_)] # if a parent has one child, all the production of the child comes from that parent data_tree[ number_of_children == 1, processed_to_child := parent_qty_processed * extractionRate, processed_to_child ] data_tree[production_of_child == 0, processed_to_child := 0] # assigning the entired availability to processed for parent having only processed as utilization data_tree[ number_of_children == 1 & unique_proc == TRUE, processed_to_child := availability * extractionRate ] # mirror assignment for imputing processed quantity for multple parent children # 5 loop is sufficient to deal with all the cases for (k in 1:5) { data_tree <- RemainingToProcessedParent(data_tree) data_tree <- RemainingProdChildToAssign(data_tree) } data_tree <- RemainingToProcessedParent(data_tree) # proportional allocation of the remaing production of multiple parent children data_tree[, processed_to_child := ifelse( number_of_parent > 1 & is.na(processed_to_child), (remaining_to_process_child * is.na(processed_to_child) * remaining_processed_parent) / sum((remaining_processed_parent * is.na(processed_to_child)), na.rm = TRUE), processed_to_child), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # Update of remaining production to assing ( should be zero for 2000:2013) data_tree[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate,na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data_tree[ remaining_processed_parent < 0, remaining_processed_parent := 0 ] # Impute processed quantity for 2014 onwards using 3 years average # (this only to imput shareDownUp) data_tree <- data_tree[ order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), processed_to_child_avg := rollavg(processed_to_child, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") ] setkey(data_tree, NULL) data_tree[timePointYears > focus_interval[1]-1 & is.na(processed_to_child), processed_to_child := processed_to_child_avg] # Back to zeroweight cases(we assign to zeroweights the processed quantity of their coproduct(already calculated)) zw_coproduct_bis <- merge( data_tree, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) zw_coproduct_bis[, `:=`( measuredItemChildCPC = zeroweight, processed_to_child = processed_to_child / extractionRate ) ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") zw_coproduct_bis <- zw_coproduct_bis[, c(sel_vars, "processed_to_child"), with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk zw_coproduct_bis[, processed_to_child := sum(processed_to_child, na.rm = TRUE), by = sel_vars ] zw_coproduct_bis <- unique(zw_coproduct_bis, by = colnames(zw_coproduct_bis)) data_zeroweight <- dt_left_join(data_zeroweight, zw_coproduct_bis, by = sel_vars) data_zeroweight[, processed_to_child := processed_to_child * extractionRate ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "number_of_parent", "parent_qty_processed", "production_of_child", "processed_to_child") data_zeroweight <- data_zeroweight[, sel_vars, with = FALSE] data_tree <- data_tree[, sel_vars, with = FALSE] #combining zeroweight and non zero weight commodities data_tree <- rbind(data_tree, data_zeroweight) #calculate ShareDownUp data_tree[, shareDownUp := processed_to_child / sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] #some corrections... data_tree[is.na(shareDownUp) & number_of_parent == 1, shareDownUp := 1] data_tree[ (production_of_child == 0 | is.na(production_of_child)) & measuredItemChildCPC %!in% zeroWeight & timePointYears < focus_interval[1], shareDownUp := 0 ] data_tree[ (parent_qty_processed == 0 | is.na(parent_qty_processed)) & timePointYears < focus_interval[1], shareDownUp :=0 ] data_tree[is.na(shareDownUp), shareDownUp := 0] data_tree <- unique( data_tree[, c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "shareDownUp"), with = FALSE ] ) ########################GENERARING ProcessedShare for parent---------------------------------------- ######################## ANd ShareUpDown for children ############################################## #################################################################################################### dataProcessingShare[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), #by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) by = c(p$geoVar, p$yearVar, p$parentVar) ] dataProcessingShare[,SumLoss:=sum( Value[measuredElementSuaFbs=="loss" & timePointYears %in% focus_interval],na.rm = TRUE ), by=c("geographicAreaM49","measuredItemParentCPC") ] dataProcessingShare[,SumProd:=sum( Value[measuredElementSuaFbs=="production" & timePointYears %in% focus_interval],na.rm = TRUE ), by=c("geographicAreaM49","measuredItemParentCPC") ] dataProcessingShare[,parent_qty_processed:=Value[measuredElementSuaFbs=="foodManufacturing"], by=c("geographicAreaM49","measuredItemParentCPC","timePointYears") ] dataProcessingShare[,Prod:=Value[measuredElementSuaFbs=="production"], by=c("geographicAreaM49","measuredItemParentCPC","timePointYears") ] dataProcessingShare[,RatioLoss:=SumLoss/SumProd] dataProcessingShare[, loss_Median_before := median( Value[measuredElementSuaFbs == "loss" & timePointYears %in% 2000:focus_interval[1]-1], na.rm=TRUE ), by = c(p$parentVar, p$geoVar) ] dataProcessingShare[,NewLoss:=ifelse(is.na(loss_Median_before),TRUE,FALSE)] # dataset containing the processed quantity of parents dataProcessingShare <- unique( dataProcessingShare[, c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Prod", "availability","RatioLoss","NewLoss","parent_qty_processed"), with = FALSE ], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Prod", "availability","RatioLoss","NewLoss","parent_qty_processed") ) #setnames(dataProcessingShare, "Value", "Prod") # Processing share and ShareUpDown dataProcessingShare <- unique( dataProcessingShare[, c("geographicAreaM49", "timePointYears", "availability", "measuredItemParentCPC", "parent_qty_processed", "RatioLoss","NewLoss","Prod"), with = FALSE ], by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "parent_qty_processed") ) dataProcessingShare[timePointYears %in% focus_interval, parent_qty_processed := NA_real_] #correction of Pshare to adjust prcessed in case of new Loss dataProcessingShare[is.na(RatioLoss),RatioLoss:=0] dataProcessingShare[is.na(Prod),Prod:=0] dataProcessingShare[, Pshare := ifelse(NewLoss==TRUE,(parent_qty_processed-RatioLoss*Prod) / availability, parent_qty_processed / availability), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] dataProcessingShare[Pshare > 1, Pshare := 1] dataProcessingShare[Pshare < 0,Pshare := 0] dataProcessingShare[is.nan(Pshare), Pshare := NA_real_] dataProcessingShare <- dataProcessingShare[ order(geographicAreaM49, measuredItemParentCPC, timePointYears), Pshare_avr := rollavg(Pshare, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC") ] setkey(dataProcessingShare, NULL) # we estimate Pshare for 2014 onwards, even if processed are modified manually because a this stage # availability of 2014 onwards are known (stocks are not generated yet) dataProcessingShare[timePointYears > focus_interval[1]-1, Pshare := Pshare_avr] dataProcessingShare[, Pshare_avr := NULL] data_Pshare <- dataProcessingShare[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "parent_qty_processed", "Pshare"), with = FALSE ] # calculating shareUpdown for each child data_ShareUpDoawn <- dataComplete[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "parent_qty_processed", "measuredItemChildCPC", "extractionRate", "production_of_child", "number_of_children"), with = FALSE ] data_ShareUpDoawn <- unique( data_ShareUpDoawn, by = colnames(data_ShareUpDoawn) ) data_ShareUpDoawn <- merge( data_ShareUpDoawn, data_tree, by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), all = TRUE ) data_ShareUpDoawn <- data_ShareUpDoawn[measuredItemChildCPC %!in% zeroWeight] data_ShareUpDoawn[, shareUpDown := NA_real_] # Giulia: qui inserire una condizione, se parent qty processed =na la shares Up Down ==0 . cosi risolvi cherries e oil of linseed data_ShareUpDoawn[ extractionRate>0, shareUpDown := ifelse( !is.na(parent_qty_processed),(production_of_child / extractionRate) * shareDownUp / sum(production_of_child / extractionRate * shareDownUp, na.rm = TRUE),0), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] data_ShareUpDoawn[is.nan(shareUpDown), shareUpDown := NA_real_] data_ShareUpDoawn <- data_ShareUpDoawn[ order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), shareUpDown_avg := rollavg(shareUpDown, order = 3), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") ] setkey(data_ShareUpDoawn, NULL) data_ShareUpDoawn[timePointYears > focus_interval[1]-1, shareUpDown := shareUpDown_avg] data_ShareUpDoawn[, shareUpDown_avg := NULL] data_ShareUpDoawn[ timePointYears > focus_interval[1]-1, shareUpDown := shareUpDown / sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "shareUpDown") data_ShareUpDoawn_final <- data_ShareUpDoawn[, sel_vars, with = FALSE] shareUpDown_zeroweight <- merge( data_ShareUpDoawn_final, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) shareUpDown_zeroweight[, measuredItemChildCPC := zeroweight] shareUpDown_zeroweight <- shareUpDown_zeroweight[, sel_vars, with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk shareUpDown_zeroweight<- shareUpDown_zeroweight[, shareUpDown := sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") ] shareUpDown_zeroweight <- unique( shareUpDown_zeroweight, by = colnames(shareUpDown_zeroweight) ) # /correction data_ShareUpDoawn_final <- rbind(data_ShareUpDoawn_final, shareUpDown_zeroweight) # some correction data_ShareUpDoawn_final[is.na(shareUpDown), shareUpDown := 0] data_ShareUpDoawn_final[!is.na(shareUpDown), flagObservationStatus := "I"] data_ShareUpDoawn_final[!is.na(shareUpDown), flagMethod := "c"] # sAVE DATA TO SWS shareUpDown_to_save <- copy(data_ShareUpDoawn_final) shareUpDown_to_save[, measuredElementSuaFbs := "5431"] setnames( shareUpDown_to_save, c("measuredItemParentCPC", "measuredItemChildCPC"), c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree") ) setnames(shareUpDown_to_save, "shareUpDown", "Value") sessionKey_shareUpDown <- swsContext.datasets[[1]] CONFIG <- GetDatasetConfig(sessionKey_shareUpDown@domain, sessionKey_shareUpDown@dataset) # taking updown shares from the session data_shareUpDown_sws <- GetData(sessionKey_shareUpDown) shareUpDown_to_save <- shareUpDown_to_save[timePointYears %in% startYear:endYear,] faosws::SaveData( domain = "suafbs", dataset = "up_down_share", data = shareUpDown_to_save[measuredItemParentCPC_tree %in% Item_Parent, ], waitTimeout = 20000 ) print("Tree corrected succesfully") <file_sep>/modules/productionDerivedCalculation/main.R ##' # Imputation Processed Commodities ##' ##' **Author: <NAME>** ##' Modified by NW to include al SUA components for availability and reverted function elementToCodes2 ##' back to its original version ##' ##' **Description:** ##' ##' ##' ##' **Inputs:** ##' ##' 1. commodity tree ##' 2. SUA data (restricted to the components I need: Prod, Trade, Stock, Seed) ##' ##' ##' ##' **Steps:** ##' ##' 1. Build the imputation key and pull the data necessary ##' ##' ##' 2. Compute Share "DownUp" ##' ##' 3. Compute Processing share ##' ##' **Data scope** ##' ##' * GeographicAreaM49: The user can decide if apply the procedure to the country queried in the session ##' or to "all". "all" picks its Value from the production completeImputationKey (stored in the data.table: ##' fbs_production_comm_codes) ##' ##' * measuredItemCPC: the list of item involved in this process is stored in the SWS, in the table ##' processed_item ##' ##' * timePointYears: All years specified in tha range selected by the user start_year-end_year. ##' It is requested also to specifi the first year for which we need to produce imputations ##' The module authomatically protecte all the figures up to this year ##' ##' --- ##' Initialisation ##' suppressMessages({ library(data.table) library(faosws) library(faoswsFlag) library(faoswsUtil) library(faoswsImputation) library(faoswsProduction) library(faoswsProcessing) library(faoswsEnsure) library(magrittr) library(dplyr) library(sendmailR) library(faoswsStandardization) }) # # top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, # 324,332,356,360,368,384,404,116,408,450,454,484,508, # 524,562,566,586,604,608,716,646,686,762,834,764,800, # 854,704,231,887,894,760,862,860) R_SWS_SHARE_PATH <- Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ library(faoswsModules) SETTINGS = ReadSettings("modules/productionDerivedCalculation/sws.yml") ## If you're not on the system, your settings will overwrite any others R_SWS_SHARE_PATH = SETTINGS[["share"]] ## Define where your certificates are stored SetClientFiles(SETTINGS[["certdir"]]) ## Get session information from SWS. Token must be obtained from web interface GetTestEnvironment(baseUrl = SETTINGS[["server"]], token = SETTINGS[["token"]]) # dir=paste0("C:/Work/SWS/FBS/Production/DerivedProduction/Output/") dir=getwd() } sessionKey = swsContext.datasets[[1]] ########################################################################################################### ##Create a new directories in the share env to support the validation: #dir_to_save <- "//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Output/" dir_to_save <- file.path(R_SWS_SHARE_PATH, "processedItem_SUA",paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username))))) if(!file.exists(dir_to_save)){ dir.create(dir_to_save, recursive = TRUE) } # dir_to_save_plot <- file.path(R_SWS_SHARE_PATH, "processedItem", paste0("validation", gsub("/", "_",swsContext.username)),"plot") dir_to_save_plot <- file.path(R_SWS_SHARE_PATH, "processedItem_SUA", paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username)))),"plot") # dir_to_save_plot <- "//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Plot" if(!file.exists(dir_to_save_plot)){ dir.create(dir_to_save_plot, recursive = TRUE) } # dir_to_save_plot <- file.path(R_SWS_SHARE_PATH, "processedItem", paste0("validation", gsub("/", "_",swsContext.username)),"plot") dir_to_save_neg <- file.path(R_SWS_SHARE_PATH, "processedItem_SUA", paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username)))),"neg") # dir_to_save_plot <- "//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Plot" if(!file.exists(dir_to_save_neg)){ dir.create(dir_to_save_neg, recursive = TRUE) } dir_to_save_shares <- file.path(R_SWS_SHARE_PATH, "processedItem_SUA", paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username)))),"shares") if(!file.exists(dir_to_save_shares)){ dir.create(dir_to_save_shares, recursive = TRUE) } # dir_to_save_output <- file.path(R_SWS_SHARE_PATH, "processedItem",paste0("validation", gsub("/", "_",swsContext.username)), "output") #dir_to_save_output <- "//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Output/" dir_to_save_output <- file.path(R_SWS_SHARE_PATH, "processedItem_SUA",paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username)))), "output") if(!file.exists(dir_to_save_output)){ dir.create(dir_to_save_output, recursive = TRUE) } # dir_to_save_recovery<- file.path(R_SWS_SHARE_PATH, "processedItem",paste0("validation", gsub("/", "_",swsContext.username)), "recovery") # dir_to_save_recovery <- "//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Recovery/" dir_to_save_recovery<- file.path(R_SWS_SHARE_PATH, "processedItem_SUA",paste0("validation_", gsub("/", "_",substr(swsContext.username,11, nchar(swsContext.username)))), "recovery") if(!file.exists(dir_to_save_recovery)){ dir.create(dir_to_save_recovery, recursive = TRUE) } ########################################################################################################### ##'This are those commodity that are pubblished on FAOSTAT ##'I build the key, always the same in the PRODUCTION sub modules: ##completeImputationKey=getCompleteImputationKey("production") FBScountries=ReadDatatable("fbs_countries")[,code] FBSItems=ReadDatatable("fbs_tree")[,item_sua_fbs] ##---------------------------------------------------------------------------------------------------------- ##' Get default parameters params = defaultProcessedItemParams() processedCPC=ReadDatatable("processed_item")[,measured_item_cpc] toBePubblished=ReadDatatable("processed_item")[faostat==TRUE,measured_item_cpc] ############################################################################################################# ##' Get the commodity tree from the TREE DATASET: ##' The country dimention depends on the session: geoImputationSelection = swsContext.computationParams$imputation_country_selection sessionCountry=getQueryKey("geographicAreaM49", sessionKey) selectedCountry = switch(geoImputationSelection, "session" = sessionCountry, "all" = FBScountries) # selectedCountry = selectedCountry[!selectedCountry%in%top48FBSCountries] Validation_Param = swsContext.computationParams$Validation ##--------------------------------------------------------------------------------------------------------- ##' Get the list of processed items to impute ItemImputationSelection = swsContext.computationParams$Items sessionItems=getQueryKey("measuredItemFbsSua", sessionKey) sessionItems = switch(ItemImputationSelection, "session" = sessionItems, "all" = FBSItems) ##' The year dimention depends on the session: startYear=as.integer(swsContext.computationParams$startYear) # imputationStartYear = startYear imputationStartYear=as.integer(swsContext.computationParams$startImputation) endYear = as.integer(swsContext.computationParams$endYear) endYear=2017 areaKeys=selectedCountry ##'Check on the consistency of startYear, andYear if(startYear>=endYear){ stop("You must select startYear lower than endYear") } timeKeys=as.character(c(startYear:endYear)) if(!(imputationStartYear>=startYear & imputationStartYear<=endYear)){ stop("imputationStartYear must lie in the time window between startYear and EndYear") } ##' I have to pull all the items in the parent and child columns: itemKeysParent=GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemParentCPC_tree")[,code] itemKeysChild=GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemChildCPC_tree")[,code] ##' To save time I pull just the only element I need: "extraction rate" whose code is 5423 elemKeys=c("5423") allCountries=areaKeys ##' Seven Pilot countries # allCountries=c("454", "686", "1248", "716","360", "392", "484") # allCountries=c("56") allLevels=list() forValidationFile=list() #logConsole1=file("modules/processedItems/logProcessed.txt",open = "w") #sink(file = logConsole1, append = TRUE, type = c( "message")) ##' Loop by country ##' start.time <- Sys.time() for(geo in seq_along(allCountries)){ finalByCountry=list() currentGeo=allCountries[geo] ##' Subset the data (SUA) message(paste0("Pull commodity tree for country: ", currentGeo) ) keyTree = DatasetKey(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = currentGeo), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemParentCPC_tree = Dimension(name = "measuredItemParentCPC_tree", keys = itemKeysParent), measuredItemChildCPC_tree = Dimension(name = "measuredItemChildCPC_tree", keys = itemKeysChild), timePointYears = Dimension(name = "timePointYears", keys = timeKeys) )) tree = GetData(keyTree) #tree = try(setTimeOut({GetData(keyTree);}, # timeout=180, onTimeout="error"), silent = TRUE) #if(!inherits(tree, "try-error")) { if(nrow(tree)<1) {message(paste0("The commodity-tree does not exist for the country: "), currentGeo)}else{ ##' I modify the structure of the tree to make it compliant with the rest of the routine: setnames(tree, c("measuredItemParentCPC_tree", "measuredItemChildCPC_tree"),c("measuredItemParentCPC", "measuredItemChildCPC")) setnames(tree, "Value", "extractionRate") tree[,flagObservationStatus:=NULL ] tree[,flagMethod:=NULL ] tree[,measuredElementSuaFbs:=NULL ] ##' I delete all the connection where no extraction rate is available: tree=tree[!is.na(extractionRate)] tree=tree[extractionRate!=0] if(nrow(tree)<1) {message(paste0("The commodity-tree conteins only ZERO extraction rates in the country: "), currentGeo)}else{ ##' I associate the level to each parent-child combination, this operation is done by country-year combinations ##' because the commodity tree may change across countries and over time. ##' The uniqueLevel represents all the country-year comb. uniqueLevels = tree[, .N, by = c("geographicAreaM49", "timePointYears")] uniqueLevels[, N := NULL] levels=list() treeLevels=list() for (i in seq_len(nrow(uniqueLevels))) { filter=uniqueLevels[i, ] treeCurrent=tree[filter, , on = c("geographicAreaM49", "timePointYears")] levels=findProcessingLevel(treeCurrent,"measuredItemParentCPC","measuredItemChildCPC") setnames(levels, "temp","measuredItemParentCPC") treeLevels[[i]]= merge(treeCurrent, levels, by=c("measuredItemParentCPC"), all.x=TRUE) } tree=rbindlist(treeLevels) tree = tree %>% dplyr::group_by_("geographicAreaM49","timePointYears","measuredItemChildCPC") %>% dplyr::mutate(processingLevel = max(processingLevel,na.rm=TRUE)) tree = as.data.table(tree) ##------------------------------------------------------------------------------------------------------------------------------------- ############################################################################################################################ ##' Select all the commodity involved (what I need is just the dependence parent-child, ##' all the possibilities, no country-year specific) treeRestricted=tree[,.(measuredItemParentCPC,measuredItemChildCPC,processingLevel)] treeRestricted=treeRestricted[with(treeRestricted, order(measuredItemChildCPC))] treeRestricted=treeRestricted[!duplicated(treeRestricted)] if(ItemImputationSelection=="session") { processedCPC = processedCPC[processedCPC%in%sessionItems] } ##' Get all the primary starting from the processed item (stored in the data.table: processed_item ) primaryInvolved=getPrimary(processedCPC, treeRestricted, params) #Sumeda : primaryInvolvedDescendents inlcudes all primaries and its related processed items. However, the processed items are stored in "processedCPC" #where it is generated using a data table called "processed_items". This list is not complete. Some processed commodities are ignored. # # # ##' Get all the children of primary commodities involved (all levels) # primaryInvolvedDescendents=getChildren( commodityTree = treeRestricted, # parentColname ="measuredItemParentCPC", # childColname = "measuredItemChildCPC", # topNodes =primaryInvolved ) # # #Sumeda : Creates "primaryInvolvedDescendents" vector in such a way that it includes all parent, child in the tree. primaryInvolvedDescendents <- unique(c(treeRestricted$measuredItemParentCPC, treeRestricted$measuredItemChildCPC)) ##' For some countris (not included in the FBS country list) there are no processed commodities to be imputed, ##' and the next steps cannot be run. if(length(primaryInvolvedDescendents)==0) {message("No primary commodity involved in this country")}else{ ##' Find the so-called secondLoop commodities: ##' select all the unique combination of country-year-commodity-level: ##' multipleLevels=unique(tree[,.( geographicAreaM49,timePointYears, measuredItemChildCPC, processingLevel)]) ##' count all the repeated country-commodity combinations. multipleLevels[,n:=.N, by=c("measuredItemChildCPC", "geographicAreaM49", "timePointYears")] ##' the n>1 it means that that commodity appears at least for one country in more tham one level. ##' If this situation occurs just for some countries (and not for all), it is not a problem, because at the end of the process we decide ##' to keep only ONE production-contribution and in particular the contribution of the highest level in the tree- ##' hierachy (if it is just one level, we are properly considering ALL the production components) ##' see row 560 of this script. secondLoop=unique(multipleLevels[n!=1,measuredItemChildCPC]) ############################################################################################################################ ##' Get SUA data from QA: all components are stored in the SWS ##' Note Restricted means that I am pulling only the components I need in this submodule: PRODUCTION, STOCK, SEED, TRADE # dataSuaRestricted=getSUADataRestricted() ############################################################################################################################ ## Get from SUA importCode = "5610" exportCode = "5910" productionCode="5510" seedCode="5525" stocksCode = "5071" FeedCode = "5520" LossCode = "5016" message("Pulling data from SUA_unbalanced") geoDim = Dimension(name = "geographicAreaM49", keys = currentGeo) eleDim = Dimension(name = "measuredElementSuaFbs", keys = c("5510", "5610", "5071", "5023", "5910", "5016", "5165", "5520", "5525", "5164", "5166", "5141", "5113")) itemKeys = primaryInvolvedDescendents itemDim = Dimension(name = "measuredItemFbsSua", keys = itemKeys) timeDim = Dimension(name = "timePointYears", keys = timeKeys) sua_un_key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim) ) sua_unbalancedData = GetData(sua_un_key) if(nrow(sua_unbalancedData[measuredElementSuaFbs=="5510",]) > 1) { ############################################################################################################################ # dataSuaRestricted=dataSuaRestricted[timePointYears<2014] # dataSuaRestricted=rbind(dataSuaRestricted,sua_unbalancedData ) ############################################################################################################################ ##' I am using elementCodesToNames2!!!!! because it has not been deployed yet the standardization package ##' This function is upload into the package folder when I have created the plugin ##' ##' NW: changed back to elementCodestoNames (apparently function has been updated) # data = elementCodesToNames(data = dataSuaRestricted, itemCol = "measuredItemFbsSua", # elementCol = "measuredElementSuaFbs") data = elementCodesToNames(data = sua_unbalancedData, itemCol = "measuredItemFbsSua", elementCol = "measuredElementSuaFbs") ##' Add all the missing PRODUCTION row: if the production of a derived product does not exist it even if it is created by this ##' routine cannot be stored in the SUA table and consequently all the commodities that belongs to its descendents are not estimates ##' or are estimated using only the TRADE and neglecting an important part of the supply components. prod=data[measuredElementSuaFbs=="production", .( geographicAreaM49, timePointYears ,measuredItemFbsSua)] ##all=unique(data[ ,.( geographicAreaM49, timePointYears ,measuredItemParentCPC)]) ##------------------------------------------------------------ ##' all time point years timePointYears=timeKeys ##' all countries geographicAreaM49=currentGeo ##' I have to build table containing the complete data key ( I have called it: all) all1=merge(timePointYears, primaryInvolvedDescendents) setnames(all1, c("x","y"),c("timePointYears","measuredItemFbsSua")) all2=merge(geographicAreaM49, primaryInvolvedDescendents) setnames(all2, c("x","y"),c("geographicAreaM49","measuredItemFbsSua")) all1=data.table(all1) all2=data.table(all2) all=merge(all1, all2, by="measuredItemFbsSua", allow.cartesian = TRUE) ##' The object "all" contais a complete key (all countries, all years, all items) for the production element ##' To avoid duplicates I select just those row that are not already included into the SUA table ##' Note that all the columns of the all datatable have class=factor all[,measuredItemFbsSua:=as.character(measuredItemFbsSua)] all[,timePointYears:=as.character(timePointYears)] all[,geographicAreaM49:=as.character(geographicAreaM49)] noProd=setdiff(all,prod) ##' I add the value and flags columns: if(nrow(noProd)>0){ noProd=data.table(noProd, measuredElementSuaFbs="production",Value=NA,flagObservationStatus="M",flagMethod="u" ) ##' I add this empty rows into the SUA table data=rbind(data,noProd) } ############################################################################################################################ ##-------------------------------------------------------------------------------------------------------------------------- ##' Processed data (OUTPUT). I pull the data from the aproduction domain. Baasically I am pulling the already existing ##' production data, ##' Restrict the complete imputation keys in ordert to pull only PRODUCTION: ## dataProcessedImputationKey = DatasetKey(domain = "agriculture", dataset = "aproduction", ## dimensions = list( ## geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = selectedCountry), ## measuredElement = Dimension(name = "measuredElement", keys = c(productionCode)), ## measuredItemCPC = Dimension(name = "measuredItemCPC", keys = primaryInvolvedDescendents), ## timePointYears = Dimension(name = "timePointYears", keys = timeKeys)) ## ) ## ## ## dataProcessed=GetData(dataProcessedImputationKey) dataProcessed=sua_unbalancedData[measuredElementSuaFbs=="5510"] setnames(dataProcessed,c("measuredElementSuaFbs","measuredItemFbsSua"),c("measuredElement","measuredItemCPC")) dataProcessed[,timePointYears:=as.numeric(timePointYears)] dataProcessed=dataProcessed[,benchmark_Value:=Value] ##' Artificially protect production data between the time window external to the range I have to produce imputations: ##dataProcessed[timePointYears<imputationStartYear,flagObservationStatus:="E"] ##dataProcessed[timePointYears<imputationStartYear,flagMethod:="h"] dataProcessed=expandYear(dataProcessed,newYear=as.numeric(endYear)) dataProcessed=removeInvalidFlag(dataProcessed, "Value", "flagObservationStatus", "flagMethod", normalised = TRUE) dataProcessed=removeNonProtectedFlag(dataProcessed, "Value", "flagObservationStatus", "flagMethod", normalised = TRUE, keepDataUntil =imputationStartYear) setnames(dataProcessed, "measuredItemCPC", "measuredItemChildCPC") ##' At the moment we have SUA data for the time range 2000-2015 (I pulled data from QA) ##' data:SUA (if I pulled data from SWS (the name of the ITEM column is different: measuredItemFbsSua)) ##' I keep only the item theat I need: processed Items and all those items in them trees data=data[measuredItemFbsSua %in% primaryInvolvedDescendents] data=data[!is.na(measuredElementSuaFbs),] ##' change the name of the ITEM columns: parents setnames(data,"measuredItemFbsSua","measuredItemParentCPC") ##----------------------------------------------------------------------------------------------------------------------- ##' the loop works on processing levels: levels=unique(tree[, processingLevel]) data[,timePointYears:=as.numeric(timePointYears)] tree[,timePointYears:=as.character(timePointYears)] tree[,timePointYears:=as.numeric(timePointYears)] #data=data[geographicAreaM49==currentGeo] ##' Tresform TIME in a numeric variabible: ## data[,timePointYears:=as.numeric(timePointYears)] ##' Subset PRODUCTION data ##dataProcessed=dataProcessed[geographicAreaM49==currentGeo] #dataProcessed[,timePointYears:=as.numeric(timePointYears)] data$PG1 = NA for(lev in (seq_along(levels)-1)) { ##' Loop by level treeCurrentLevel=tree[processingLevel==lev] message("Processing country ", currentGeo, " - level ", lev ) ##' To compute the PRODUCTION I need to evaluate how much (which percentage) of ##' the parent commodity availability is allocated in the productive process associate ##' to a specific child item. ##' Calculate share down up. Please note that currentData contains the SUA table. ##' NW: use all SUA components dataMergeTree=calculateShareDownUpFBS(data=data,tree=treeCurrentLevel, params=params, printDirectory = dir_to_save_neg, printNegativeAvailability=TRUE,useAllSUAcomponents=FALSE) ##' Here I merge the SUA table (already merged with tree), with the PRODUCTION DATA ##' This merge produces many NA because dataProcessed contains all the derived item (and not just ##' those at the level of the loop) inputOutputdata= merge(dataMergeTree,dataProcessed, by=c("geographicAreaM49","measuredItemChildCPC","timePointYears"),all.y=TRUE) inputOutputdata[shareDownUp=="NaN",shareDownUp:=0] inputOutputdata$PG1 = NA inputOutputdata=calculateProcessingShareFBS_NW(inputOutputdata, param=params) ##------------------------------------------------------------------------------------------------------------------------------------- ##inputOutputdata[, meanProcessingShare:=mean(processingShare, na.rm = TRUE), by=c("geographicAreaM49","measuredItemChildCPC","measuredItemParentCPC")] ##inputOutputdata[is.na(processingShare)&!is.na(meanProcessingShare),processingShare:=meanProcessingShare ] inputOutputdata[, newImputation:=availability*processingShare*extractionRate] finalByCountry[[lev+1]]=inputOutputdata ##' Update production in data in order to add the just computed production ##' at each loop we compute production for the following level, this prodution ##' should be used in the following loop to compute the availabilities updateData=inputOutputdata[,.(geographicAreaM49, timePointYears, measuredItemChildCPC, newImputation, PG1)] updateData[, newImputation:=sum(newImputation,na.rm = TRUE), by=c("geographicAreaM49", "timePointYears", "measuredItemChildCPC")] updateData=unique(updateData) ##' I change the column names bacause the commodities that now are children will be parent in the next loop setnames(updateData,"measuredItemChildCPC","measuredItemParentCPC") ##' I merge the new results into the SUA table data=merge(data,updateData, by=c("geographicAreaM49", "timePointYears", "measuredItemParentCPC"), all.x=TRUE) data$PG1.x[is.na(data$PG1.x)] = data$PG1.y[is.na(data$PG1.x)] data$PG1= data$PG1.x data[,PG1.x:=NULL] data[,PG1.y:=NULL] ##' Olnly non-protected production figures have to be overwritten: data[,flagComb:=paste(flagObservationStatus,flagMethod,sep=";")] flagValidTable=copy(flagValidTable) flagValidTable=flagValidTable[Protected==TRUE,] protected=flagValidTable[,protectedComb:=paste(flagObservationStatus,flagMethod,sep=";")] protected=protected[,protectedComb] data[geographicAreaM49==currentGeo & !(flagComb %in% protected)& measuredElementSuaFbs=="production" & !is.na(newImputation) & !(measuredItemParentCPC %in% secondLoop) & timePointYears>=imputationStartYear, ":="(c("Value","flagObservationStatus","flagMethod"),list(newImputation,"I","e"))] data[,newImputation:=NULL] data[,flagComb:=NULL] } allLevelsByCountry=rbindlist(finalByCountry) secondLoopChildren=getChildren( commodityTree = treeRestricted, parentColname ="measuredItemParentCPC", childColname = "measuredItemChildCPC", topNodes =secondLoop ) ##' Note that the so called "secondLoop" items are computed for each country separately: secondLoop=secondLoopChildren ##' This passage is to sum up the productions of a derived commodities coming from more ##' than one parent (those commodities are flagged as second-loop). To identify the highest ##' level of the hierarchy I have to choose the min value in the processingLevel column. allLevelsByCountry[, minProcessingLevel:=NA_real_] ##' The min of the processing-level is not only item-specific, but also country-time specific, since the ##' the commodity-tree may change over the time and the countries. # allLevelsByCountry = as.data.frame(allLevelsByCountry) # # allLevelsByCountry[measuredItemChildCPC %in% secondLoop, minProcessingLevel:=min(processingLevel), by=c("geographicAreaM49","timePointYears", "measuredItemChildCPC")] # # allLevelsByCountry[measuredItemChildCPC %in% secondLoop & extractionRate!=0, minProcessingLevel:=min(processingLevel), # by=c("geographicAreaM49","timePointYears", "measuredItemChildCPC")] # NW: This is not just removing contributions from lower items in the same hierarchy, but also contributions at lower levels # in the production chain coming from another branch ##' I remove (just for those commodities classified as secondLoop) the production-contributions coming from parents ##' lower in the hierachy (it means with an higher processing-level) # allLevelsByCountry=allLevelsByCountry[(is.na(minProcessingLevel) | processingLevel==minProcessingLevel) & extractionRate!=0] # Here either sum across parents by child or send email. #finalOutput = output[!(measuredItemChildCPC %in% secondLoop), list(newImputation = sum(newImputation, na.rm = TRUE)), # by =c ("geographicAreaM49","measuredItemChildCPC","timePointYears")] allLevels[[geo]]=allLevelsByCountry ## create an intermediate set of data to be saved in a shared folder forValidationFile[[geo]]= allLevels[[geo]][,.(geographicAreaM49, measuredItemChildCPC, timePointYears, measuredItemParentCPC ,extractionRate ,processingLevel,processingShare, availability ,shareDownUp ,newImputation, minProcessingLevel, benchmark_Value)] setnames(forValidationFile[[geo]], c("measuredItemChildCPC","measuredItemParentCPC"), c("measuredItemChildCPC_tree","measuredItemParentCPC_tree")) forValidationFile[[geo]]= nameData("suafbs", "ess_fbs_commodity_tree2", forValidationFile[[geo]]) # forValidationFile[[geo]][,timePointYears:=as.numeric(timePointYears)] dataLabel=copy(data) dataLabel=dataLabel[geographicAreaM49==currentGeo] setnames(dataLabel, "measuredItemParentCPC", "measuredItemChildCPC_tree") dataLabel=nameData("suafbs", "ess_fbs_commodity_tree2", dataLabel) dataLabel[,timePointYears_description:=NULL] setnames(dataLabel, c("measuredElementSuaFbs", "Value"), c("measuredElementSuaFbs_child", "Value_child")) forValidationFile[[geo]]=merge(dataLabel,forValidationFile[[geo]], by=c("geographicAreaM49","measuredItemChildCPC_tree", "measuredItemChildCPC_tree_description", "geographicAreaM49_description", "timePointYears") , allow.cartesian = TRUE) forValidationFile[[geo]]=forValidationFile[[geo]][,.(geographicAreaM49,geographicAreaM49_description,timePointYears, measuredItemChildCPC_tree,measuredItemChildCPC_tree_description , measuredItemParentCPC_tree,measuredItemParentCPC_tree_description, measuredElementSuaFbs_child ,Value_child, flagObservationStatus, flagMethod, availability , extractionRate, processingLevel,benchmark_Value, newImputation, shareDownUp,processingShare,minProcessingLevel)] ## Save all the intermediate output country by country: if(!CheckDebug()){ try(write.csv(allLevels[[geo]], file=file.path(dir_to_save_recovery,paste0(currentGeo,".csv")), row.names = FALSE), silent = TRUE) try(write.csv(forValidationFile[[geo]], file=file.path(dir_to_save_output,paste0(currentGeo,".csv")), row.names = FALSE), silent = TRUE) } } } } } #}else{message(paste0("TimeOut issues to GetData for country: ",currentGeo))} } end.time <- Sys.time() #------------------------------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------------------------------- output=rbindlist(allLevels) ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### #Sumeda: Modified the code in order to adjust the shares of coprudcuts. There are cases where the co-products have different #processing shares that is not acceptable. Tomarsz provided a table that indicates the relationship between the co-products. #With the help of this table, a new processing share has been adjusted for the coproducts in order to maintain simillar shares. coproduct_table <- ReadDatatable('zeroweight_coproducts') coproduct_table <- coproduct_table[,c("measured_item_child_cpc","branch"), with = FALSE] coproduct_table <- setNames(coproduct_table, c("measuredItemChildCPC","branch")) # if (nrow(coproduct_table[measuredItemChildCPC == branch]) > 0) { # stop("There's an error in the co-product table.") # } # Can't do anything if this information if missing, so remove these cases coproduct_table <- coproduct_table[!is.na(branch)] %>% tbl_df() %>% # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # XXX removing these cases as '22242.01' appears as zero-weight for main product = '22110.04' X # XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX dplyr::filter(branch != '22242.01 + 22110.04') # If TRUE it means that "+" or "or" cases are involved fmax <- function(child, main, share, plusor = FALSE) { main <- unique(main) if (plusor) { found <- sum(sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)) if (found == 0) { return(max(share, na.rm = TRUE)) } else if (found == 1) { return(share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]]) } else { # should be 2 return(max(share[(1:length(child))[sapply(child, function(x) grepl(x, main), USE.NAMES = FALSE)]], na.rm = TRUE)) } } else { if (sum(grepl(main, child)) > 0) { share[child == main] } else { max(share, na.rm = TRUE) } } } ################################# Easy cases coproduct_table_easy <- coproduct_table %>% dplyr::filter(!grepl('\\+|or', branch)) coproduct_table_easy <- bind_rows( coproduct_table_easy, coproduct_table_easy %>% dplyr::mutate(measuredItemChildCPC = branch) ) %>% distinct() output_easy <- output[measuredItemChildCPC %in% unique(coproduct_table_easy$measuredItemChildCPC)] %>% tbl_df() if (nrow(output_easy) > 0) { output_easy <- output_easy %>% left_join(coproduct_table_easy, by = 'measuredItemChildCPC') %>% group_by(geographicAreaM49, timePointYears, branch,measuredItemParentCPC) %>% dplyr::mutate( reference_share = fmax(measuredItemChildCPC, branch, processingShare, FALSE), # Ask whether rounding by 2 is fine reimpute = round(processingShare, 2) != round(reference_share, 2) ) %>% ungroup() } ################################# / Easy cases ################################# Plus cases coproduct_table_plus <- coproduct_table %>% dplyr::filter(grepl('\\+', branch)) coproduct_table_plus <- bind_rows( coproduct_table_plus, coproduct_table_plus %>% tidyr::separate(branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *') %>% dplyr::select(measuredItemChildCPC = main1, branch) %>% distinct(), coproduct_table_plus %>% tidyr::separate(branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *') %>% dplyr::select(measuredItemChildCPC = main2, branch) %>% distinct() ) %>% distinct() output_plus <- output[measuredItemChildCPC %in% unique(coproduct_table_plus$measuredItemChildCPC)] %>% tbl_df() if (nrow(output_plus) > 0) { output_plus <- output_plus %>% left_join(coproduct_table_plus, by = 'measuredItemChildCPC') %>% group_by(geographicAreaM49, timePointYears, branch,measuredItemParentCPC) %>% dplyr::mutate( reference_share = fmax(measuredItemChildCPC, branch, processingShare, TRUE), # Ask whether rounding by 2 is fine reimpute = round(processingShare, 2) != round(reference_share, 2) ) %>% ungroup() } ################################# / Plus cases ################################# Or cases coproduct_table_or <- coproduct_table %>% dplyr::filter(grepl('or', branch)) coproduct_table_or <- bind_rows( coproduct_table_or, coproduct_table_or %>% tidyr::separate(branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\or *') %>% dplyr::select(measuredItemChildCPC = main1, branch) %>% distinct(), coproduct_table_or %>% tidyr::separate(branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\or *') %>% dplyr::select(measuredItemChildCPC = main2, branch) %>% distinct() ) %>% distinct() output_or <- output[measuredItemChildCPC %in% unique(coproduct_table_or$measuredItemChildCPC)] %>% tbl_df() if (nrow(output_or) > 0) { output_or <- output_or %>% left_join(coproduct_table_or, by = 'measuredItemChildCPC') %>% group_by(geographicAreaM49, timePointYears, branch, measuredItemParentCPC) %>% dplyr::mutate( reference_share = fmax(measuredItemChildCPC, branch, processingShare, TRUE), # Ask whether rounding by 2 is fine reimpute = round(processingShare, 2) != round(reference_share, 2) ) %>% ungroup() } ################################# / Or cases output_to_check <- bind_rows( output_easy, output_plus, output_or ) %>% dplyr::filter(timePointYears >= imputationStartYear) %>% dplyr::mutate( processingShare = ifelse(reimpute, reference_share, processingShare), # Status I = Imputed processingShareFlagObservationStatus = ifelse(reimpute, 'I', processingShareFlagObservationStatus), # Method c = copied from somewhere else. processingShareFlagMethod = ifelse(reimpute, 'c', processingShareFlagMethod), # Redoing this, as the formula holds before and should # also hold after assigning reference_share newImputation = availability * processingShare * extractionRate ) if (nrow(output_to_check) > 0) { output <- bind_rows( anti_join( output, dplyr::select(output_to_check, -branch, -reference_share, -reimpute), by = c('geographicAreaM49', 'measuredItemParentCPC', 'measuredItemChildCPC', 'timePointYears') ), dplyr::select(output_to_check, -branch, -reference_share, -reimpute) ) %>% as.data.table() } ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ########################################################################################################################### ##' Those commodities that appear in more than one level of the commodity-tree hierachy are considered children ##' of the highest item in the hierachy. ##' I have to expand the list of secondLoop commodities: I impose that all the descentents of a second-loop ##' commodities are classified as "second-loop": #------------------------------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------------------------------- ##' The following lines create the dataset useful for validation purposes: ##' I want to sum the newImputation into the totNewImputation, but I want to keep ##' all the constributions to double check the final result BadProcessingShares = output[PG1==TRUE,] BadProcessingShares = BadProcessingShares[BadProcessingShares$Year>=imputationStartYear,] if(CheckDebug()){ output[, totNewImputation := sum(newImputation, na.rm = TRUE), by =c ("geographicAreaM49","measuredItemChildCPC","timePointYears")] ##' outPutforValidation is the file created to validate the output from team B/C outPutforValidation=copy(output) outPutforValidation=outPutforValidation[,.(geographicAreaM49,measuredItemChildCPC, timePointYears, measuredItemParentCPC, extractionRate, processingLevel ,availability,shareDownUp,processingShare,newImputation, totNewImputation)] # directory="//hqfile4/ESS/Team_working_folder/B_C/3. SUA_FBS/Validation/Output/" # dir.create(directory) # fileForValidation2(outPutforValidation,SUAdata=data , dir=directory) write.csv(outPutforValidation,"C:/Work/SWS/FBS/Production/DerivedProduction/Output/outPutforValidation.csv") if (nrow(BadProcessingShares)>1) { write.csv(BadProcessingShares,"C:/Work/SWS/FBS/Production/DerivedProduction/Output/BadProcessingShares.csv") } ##' For validation purposes it is extremly important to produce validation files filtered for those 47 ##' commodies plut flours (that are upposed to be pubblished) } #------------------------------------------------------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------------------------------------------------------- ##' Here I fisically sum by child the newImputation (that now are disaggregated by parent-contribution) finalOutput=output[, list(newImputation = sum(newImputation, na.rm = TRUE)), by =c ("geographicAreaM49","measuredItemChildCPC","timePointYears")] #output[,.(geographicAreaM49,measuredItemChildCPC,timePointYears, # measuredItemParentCPC,availability,processingShare,Value, # flagObservationStatus,flagMethod,benchmark_Value,newImputation, processingLevel)] #------------------------------------------------------------------------------------------------------------------------------------- ##' I subset the output datatable in order to make comparison between benchmark_Value (basically data already stored in the SWS) ##' and newImputations (I keep just the Value and benchmark_Value columns) orig=output[,.(geographicAreaM49,measuredItemChildCPC,timePointYears,Value,benchmark_Value,flagObservationStatus,flagMethod)] ##' This subset of output is full of duplicated rows because each child can have more than one parents, and new imputations have been preduced ##' for each of its parent. Each new imputations represent the contribution of one single parent item to the production of the derived item. orig=orig[!duplicated(orig)] ##' finalOutput contains all the newImputation (olready aggregated with respect to all the parent contribuions) imputed=merge(finalOutput,orig, by=c("geographicAreaM49", "measuredItemChildCPC","timePointYears"), allow.cartesian = TRUE) ##' Only M,u figures are overwritten by the new imputations. imputed[flagObservationStatus=="M" & flagMethod=="u" & !is.na(newImputation), ":="(c("Value", "flagObservationStatus", "flagMethod"), list(newImputation,"I","e"))] #------------------------------------------------------------------------------------------------------------------------------------- ##' The column PROTECTED is created just to PLOT the output and distinguish between new imputations and protected figures. imputed[,flagComb:=paste(flagObservationStatus,flagMethod,sep=";")] imputed[, PROTECTED:=FALSE] imputed[flagComb %in% protected, PROTECTED:=TRUE] imputed[PROTECTED==TRUE,newImputation:=benchmark_Value] # imputed[geographicAreaM49%in%top48FBSCountries] toPlot=imputed ##' This table is saved just to produce comparisond between batches: if(CheckDebug()){ write.csv(toPlot, "C:/Work/SWS/FBS/Production/DerivedProduction/Output/toPlot.csv", row.names=FALSE) res_plot = try(plotResult(toPlot, toPubblish=toBePubblished, pathToSave= "C:/Work/SWS/FBS/Production/DerivedProduction/Output/Plots")) } ##Plots goes directly to the shared folder if(!CheckDebug()){ if(nrow(BadProcessingShares) > 0) { try(write.csv(BadProcessingShares, file=file.path(dir_to_save_shares,"BadShares.csv"), row.names = FALSE), silent = TRUE) } } if(!CheckDebug() & swsContext.computationParams$Validation=="1"){ res_plot = try(plotResult(toPlot, toPubblish=toBePubblished, pathToSave= dir_to_save_plot)) } #------------------------------------------------------------------------------------------------------------------------------------- ##' Save back ##' Remove the auxiliary columns created in the process imputed[,newImputation:=NULL] imputed[,benchmark_Value:=NULL] imputed[,flagComb:=NULL] imputed[,PROTECTED:=NULL] imputed[,measuredElement:="5510"] imputed= removeInvalidDates(data = imputed, context = sessionKey) imputed= postProcessing(data = imputed) imputed=imputed[flagObservationStatus=="I" & flagMethod=="e"] imputed=imputed[,.(measuredElement,geographicAreaM49, measuredItemChildCPC, timePointYears,Value,flagObservationStatus,flagMethod)] ##' ensure that just data after the imputationStartYear are saved back and I am not overwriting ##' protected figures ##' imputed=imputed[timePointYears>=imputationStartYear] ensureProtectedDataFBS(imputed, returnData = FALSE) setnames(imputed, "measuredElement", "measuredElementSuaFbs") setnames(imputed, "measuredItemChildCPC", "measuredItemFbsSua") SaveData(domain = sessionKey@domain, dataset = sessionKey@dataset, data = imputed) if (nrow(BadProcessingShares) > 0) { from = "<EMAIL>" to = swsContext.userEmail subject = "Derived-Products imputation plugin has correctly run" body = paste0("The plug-in has saved the Production imputation in your session.", " However, some shares are greater than 1. Please check these at: ", dir_to_save_shares) sendmailR::sendmail(from = from, to = to, subject = subject, msg = body) paste0("Email sent to ", swsContext.userEmail) } if (nrow(BadProcessingShares) == 0){ print("The plugin ran successfully!") ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "Derived-Products imputation plugin has correctly run" body = paste0("The plug-in has saved the Production imputation in your session.", "You can browse charts and intermediate csv files in the shared folder: ", dir_to_save) sendmailR::sendmail(from = from, to = to, subject = subject, msg = body) paste0("Email sent to ", swsContext.userEmail) }<file_sep>/R/computeFbsAggregate.R ##' Compute FBS Aggregate ##' ##' This function takes the FBS aggregation tree and rolls up the SUA data to ##' all FBS levels. ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param fbsTree This "tree" should just have three columns: ##' standParams$parentID, standParams$childID, and standParams$extractVar ##' (which if missing will just be assigned all values of 1). This tree ##' specifies how SUA commodities get combined to form the FBS aggregates. If ##' NULL, the last step (aggregation to FBS codes) is skipped and data is ##' simply returned at SUA level. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' ##' @return A list of four data.tables, each containing the final FBS data at ##' the four different FBS levels. ##' ##' @export ##' computeFbsAggregate = function(data, fbsTree, standParams){ ## Data Quality Checks stopifnot(standParams$itemVar %in% colnames(data)) stopifnot(standParams$itemVar %in% colnames(fbsTree)) stopifnot(paste0("fbsID", 1:4) %in% colnames(fbsTree)) fbsTree[measuredItemSuaFbs=="23670.01",fbsID4:=2542] fbsTree[measuredItemSuaFbs=="23670.01",fbsID2:=2903] if(data[,unique(geographicAreaM49)]%in%c("72")){ fbsTree[measuredItemSuaFbs=="23670.01",fbsID4:=2543] fbsTree[measuredItemSuaFbs=="23670.01",fbsID2:=2903] } data = merge(data, fbsTree, by = standParams$itemVar) out = list() out[[1]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID4")] out[[2]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID3")] out[[3]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID2")] out[[4]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID1")] return(out) }<file_sep>/R/processForward.R ##' Process Forward ##' ##' A few edges in the commodity trees are labeled with an 'F' to indicate that ##' processing is 'forward'. The parent commodities in these edges are ##' immediately converted into the corresponding child and then they are removed ##' from the tree (as we will standardize to the children instead). This is a ##' rare scenario; an example commodity is sugar. ##' ##' Note: when commodities are processed forward like this, the final flag is ##' assigned ARBITRARILY as the first flag observed (for lack of a better ##' approach). This should be corrected. ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param tree The commodity tree which provides the edge structure. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' ##' @return A list of names 'data' and 'tree'. Both objects must be returned, ##' as the tree is updated by pruning off some edges. ##' processForward = function(data, tree, standParams){ ## If no forward processing edge, than don't do anything: if(all(tree[, get(standParams$targetVar) != "F"])){ return(list(data = data, tree = tree)) } cnames = colnames(data) subTree = tree[get(standParams$targetVar) == "F", ] level = getCommodityLevel(subTree, parentColname = standParams$parentVar, childColname = standParams$childVar) setnames(level, c(standParams$parentVar, "level")) if(length(unique(tree[get(standParams$parentVar) %in% subTree[, get(standParams$parentVar)], target])) > 1){ warning("Some parents have one edge set to be forward processed and ", "another edge not. How to handle such a case is not clear, ", "and this may cause strange behavior.") } subTree = merge(subTree, level, by = standParams$parentVar) setnames(subTree, standParams$parentVar, standParams$itemVar) for(currentLevel in subTree[, sort(unique(level))]){ dataToUpdate = merge(data, subTree[level == currentLevel, ], by = standParams$itemVar, allow.cartesian = TRUE) ## Process the node down by first computing the availability of the ## parent as the balance dataToUpdate = dataToUpdate[, list(parentAvail = sum(Value * ifelse(get(standParams$elementVar) %in% c(standParams$exportCode, standParams$stockCode, standParams$foodCode, standParams$foodProcCode, standParams$feedCode, standParams$wasteCode, standParams$seedCode, standParams$industrialCode, standParams$touristCode, standParams$residualCode), -1, ifelse(get(standParams$elementVar) %in% c(standParams$importCode, standParams$productionCode), 1, 0)), na.rm = TRUE), parentAvailSd = sqrt(sum(standardDeviation^2 * ifelse(get(standParams$elementVar) %in% c(standParams$exportCode, standParams$stockCode, standParams$foodCode, standParams$foodProcCode, standParams$feedCode, standParams$wasteCode, standParams$seedCode, standParams$industrialCode, standParams$touristCode, standParams$residualCode, standParams$importCode, standParams$productionCode), 1, 0), na.rm = TRUE))), by = c(standParams$mergeKey, standParams$childVar, standParams$extractVar)] dataToUpdate[, c(standParams$itemVar) := get(standParams$childVar)] dataToUpdate[, Value := get(standParams$extractVar) * parentAvail] dataToUpdate[, standardDeviation := get(standParams$extractVar) * parentAvailSd] dataToUpdate[, c(standParams$elementVar) := standParams$productionCode] dataToUpdate = dataToUpdate[, c(standParams$mergeKey, standParams$elementVar, "Value", "standardDeviation"), with = FALSE] ## Aggregate dataToUpdate in case there are multiple parents going into ## one child. dataToUpdate = dataToUpdate[, list(Value = sum(Value), standardDeviation = sqrt(sum(standardDeviation^2))), by = c(standParams$mergeKey, standParams$elementVar)] ## Add in the new data values data = merge(data, dataToUpdate, by = c(standParams$mergeKey, standParams$elementVar), all = TRUE, suffixes = c("", ".new")) data[is.na(Value), c("Value", "standardDeviation") := list(Value.new, standardDeviation.new)] data[, c("Value.new", "standardDeviation.new") := NULL] ## Remove the values processed forward from the original data data = data[!get(standParams$itemVar) %in% subTree[level == currentLevel, get(standParams$itemVar)]] } tree = tree[!get(standParams$targetVar) == "F", ] # ## This function may create some new commodities, and only the production of # ## these items will be in the data.frame. To prevent future issues, fill in # ## all other elements as well. return(list(data = data, tree = tree)) }<file_sep>/R/plotSingleTree.R ##' Plot Single Tree ##' ##' This function generates a plot for one commodity trees defined with an edge ##' list. ##' ##' @param edges A data.table with parent and child node IDs (corresponding to ##' the IDs in nodes) which specify the commodity tree structure. ##' Additionally, there should be a column with extraction rate data and a ##' column with shares data. ##' @param parentColname The column name of commodityTree which contains the ID ##' of the parent node. ##' @param childColname The column name of commodityTree which contains the ID ##' of the child node. ##' @param extractionColname The column name of commodityTree which contains the ##' extraction rate data. ##' @param dashInf Should extraction rates of infinity be represented with ##' dashes? This generally makes sense because such processing should be ##' shown on the tree but not considered in standardization. ##' @param ... Additional plotting parameers for diagram::plotmat. ##' ##' @return Generates a plot of the commodity tree as specified by edges. ##' ##' @export ##' plotSingleTree = function(edges, parentColname, childColname, extractionColname, dashInf = TRUE, ...){ if(!faosws::CheckDebug()) return(NULL) nodes = unique(c(edges[[parentColname]], edges[[childColname]])) ## Get the level for each node so we know which group to plot it in. level = getCommodityLevel(commodityTree = edges, parentColname = parentColname, childColname = childColname, returnMinLevel = FALSE) level = level[order(level), ] levelCounts = level[order(level), .N, by = "level"] ## Create an adjacency matrix to define the plotting structure. A = matrix(0, nrow = length(nodes), ncol = length(nodes)) colnames(A) = nodes rownames(A) = nodes indices = as.matrix(edges[, list(get(childColname), get(parentColname))]) indices = apply(indices, c(1, 2), as.character) A[indices] = round(edges[[extractionColname]], 2)*100 ## Create a matrix specifying curvature. Default value should be curve = merge.data.frame(level, level, by = NULL) curve$curvature = ifelse(curve$level.y >= curve$level.x, .2, 0) curve = reshape2::dcast(curve, node.x ~ node.y, value.var = "curvature") rownames(curve) = curve$node.x curve$node.x = NULL ## Reorder A based on the levels A = A[as.character(level$node), as.character(level$node)] curve = curve[as.character(level$node), as.character(level$node)] ## Configure plotting arguments plotArgs = list(...) if(!"relsize" %in% names(plotArgs)) plotArgs$relsize = 1 if(!"box.size" %in% names(plotArgs)) plotArgs$box.size = 0.03 if(!"box.type" %in% names(plotArgs)) plotArgs$box.type = "rect" if(!"shadow.size" %in% names(plotArgs)) plotArgs$shadow.size = 0 plotArgs$A = A plotArgs$pos = levelCounts$N plotArgs$curve = curve ## Plot it! plotmat = diagram::plotmat do.call(plotmat, plotArgs) } <file_sep>/R/calculateShares.R ##' calculateShares ##' ##' ##' ##' @param data The data.table containing the full dataset for standardization. ##' It should have columns corresponding to year, country, element, commodity, ##' and value. The specific names of these columns should be in params. ##' @param tree The commodity tree which details how elements can be processed ##' into other elements. It does not, however, specify which elements get ##' aggregated into others. This data.table should have columns parent, ##' child, extraction rate, share, and target (target specifying if an element ##' is processed forward or not). Names of these columns should be provided ##' in params. ##' ##' @param params The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param availability Avalaibility as previously calculated ##' @param zeroWeight as previously defined ##' @return A data.table containing the final balanced and standardized SUA ##' data. Additionally, this table will have new elements in it if ##' nutrientData was provided. ##' ##' @export ##' calculateShares=function(data=data, params=p, tree=tree,zeroWeight= zeroWeight) { # tree = merge(tree, availability, # by = c(params$childVar, params$parentVar)) tree = tree[, list(share = sum(share), availability = max(availability)), by = c(params$childVar, params$parentVar, params$extractVar, params$targetVar, params$standParentVar)] setnames(tree, "share", params$shareVar) ## Calculate the share using proportions of availability, but default to the ## old value if no "by-availability" shares are available. tree[, newShare := availability / sum(availability, na.rm = TRUE), by = c(params$childVar)] tree[, c(params$shareVar) := ifelse(is.na(newShare), get(params$shareVar), newShare)] tree[, newShare := NULL] # weight tree[,weight:=1] tree[measuredItemChildCPC %in% zeroWeight, weight:=0] freqChild= data.table(table(tree[, get(params$childVar)])) setnames(freqChild, c("V1","N"), c(params$childVar, "freq")) tree=merge(tree, freqChild , by=params$childVar) tree[availability<=0|is.na(availability), negShare:=1/freq] # tree[availability<=0, availability:=0] tree[,sumPositiveAvail:=sum(availability*ifelse(availability>0,1,0),na.rm=TRUE),by = c(params$childVar)] tree[,tempAvailability:=ifelse(availability<=0|is.na(availability),negShare*sumPositiveAvail,availability)] tree[, newShare := ifelse(tempAvailability==0,negShare, tempAvailability / sum(tempAvailability, na.rm = TRUE)), by = c(params$childVar)] tree[,availability:=tempAvailability] tree[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree[, c(params$shareVar) := ifelse(is.na(newShare), get(params$shareVar), newShare)] tree[, newShare := NULL] return(tree) } <file_sep>/R/validateTreeExtractionRates.R ##' @title Validate ExtractionRates of Commodity Trees ##' ##' @description This function perform Flag Validation for the commodity Tree ##' Validation. ##' The possible flags are (decided with Data Team): ##' ##' Extraction Rates: ##' (T,-) = validated up do 2013 - protected ##' (E,t) = copied from 2014 onwards - not protected but that do not change during standardization process ##' (E,f) = manually changed by the user - protected ##' ##' Shares: ##' (E,-) = coming from old methodology - NOT protected. These values willbe overwritten ##' at any run of the module, except the values of oils, which are kept, unless manually changed ##' (E,f) = manually changed by the user - protected ##' (I,i) = calculated by the module - not protected ##' ##' @param tree the commodity tree to check ##' ##' @param min.er the lower limit of the range of acceptable values for Extraction Rates. ##' default to 0 ##' ##' @param max.er the upper limit of the range of acceptable values for Extraction Rates. ##' default to 7 ##' ##' @return a list of two elements: ##' messageER, is a message with the information of validity of flags and ##' invalidER is a data.table which contains invalid Flags or invalid Values or is empty, if everything is valid ##' ##' @export ##' validateTreeExtractionRates = function(tree = NULL, min.er = 0, max.er = 10){ ## Data Quality Checks if(!exists("swsContext.datasets")){ stop("No swsContext.datasets object defined. Thus, you probably ", "won't be able to read from the SWS and so this function won't ", "work.") } # Checks for data stopifnot(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod") %in% colnames(tree)) if("5423"%in%tree[,measuredElementSuaFbs]){ stop("Elements have to be expressed in names: extractionRate, share") } # 5423 = Extraction Rate [hg/t] # 5431 = Share of utilization [%] tree=tree[,mget(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"))] ##create column for check ##(this column will be deleted) tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] ############################################################## #################### CHECK FLAG VALIDITY #################### ############################################################## validERflags=c("(T,-)","(E,t)","(E,f)") # if There is some invalid Flag Combination OR any value outside Ranges if(any(!(tree[measuredElementSuaFbs=="extractionRate",unique(checkFlags)]%in%validERflags))| any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]<min.er)| any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]>max.er)){ # check if Flags are invalid if(any(!(tree[measuredElementSuaFbs=="extractionRate",unique(checkFlags)]%in%validERflags))){ # if ALSO Values are invalid if(any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]<min.er)| any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]>max.er)){ # select invalid Flags rows invalidERf=tree[measuredElementSuaFbs=="extractionRate"&(!checkFlags%in%validERflags)] # select also invalid values invalidERv=tree[measuredElementSuaFbs=="extractionRate"&(Value>max.er|Value<min.er)] invalidER=rbind(invalidERf,invalidERv) invalidER[,checkFlags:=NULL] messageER = "Invalid Flags and Figures" }else{ # if ONLY Flags are invalid invalidER=tree[measuredElementSuaFbs=="extractionRate"&(!checkFlags%in%validERflags)] # then the file will contain only Flags invalidER[,checkFlags:=NULL] messageER = "Invalid Flags and Figures" } }else{ # if ONLY VALUES are INVALID if(any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]<min.er)| any(tree[measuredElementSuaFbs=="extractionRate",unique(Value)]>max.er)){ invalidER=tree[measuredElementSuaFbs=="extractionRate"&(Value>max.er|Value<min.er)] invalidER[,checkFlags:=NULL] messageER = "Invalid Flags and Figures" } } }else{ # the following Tree in empy invalidER = tree[measuredElementSuaFbs=="extractionRate"&(Value>max.er|Value<min.er)] messageER = "Extraction Rates Valid for the selected Tree" } return(list(messageER=messageER,invalidER=invalidER)) } <file_sep>/R/calculateFoodAggregates.R ##' calculateFoodAggregates ##' ##' The function creates all the Food aggregates to be displayed in the FBS. ##' This function calls the popoulation dataset in the SWS and displays population ##' in the resulting datatable ##' ##' @param standData The data.frame resulting from the standardization process ##' containing all the elements needed for the calculation of DES ##' @param params The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @return A data.table containing all the food aggregates, by country-commodity-year ##' and also containing the population by year ##' ##' @export ##' calculateFoodAggregates=function(standData=standData, params=c(),yearVals=yearVals) { p=params # first the population dataset has to be downloaded # #SWS POPULATION NEW areaKeys=standData[,unique(geographicAreaM49)] if("1248"%in%areaKeys){ areaKeys=c(areaKeys,"156") } elemKeys="511" key = DatasetKey(domain = "population", dataset = "population_unpd", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = elemKeys), timePointYears = Dimension(name = "timePointYears", keys = as.character(yearVals)) )) # #SWS POPULATION OLD # areaKeys=standData[,unique(geographicAreaM49)] # elemKeys="21" # key = DatasetKey(domain = "population", dataset = "population", dimensions = list( # geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), # measuredElementSuaFbs = Dimension(name = "measuredElementPopulation", keys = elemKeys), # timePointYears = Dimension(name = "timePointYears", keys = as.character(yearVals)) # )) popSWS=GetData(key) popSWS[geographicAreaM49=="156",geographicAreaM49:="1248"] # popSWS=popSWS[,mget(c("geographicAreaM49","measuredElement","timePointYears","Value"))] popSWS=popSWS[,mget(c("geographicAreaM49","measuredElement","timePointYears","Value"))] setnames(popSWS,"Value","population") standData= merge(standData,popSWS,by=c("geographicAreaM49","timePointYears"),all=TRUE) standData[,DESfoodSupply_kCd:=(Calories/365)/(population*1000)] standData[,proteinSupplyQt_gCd:=(Proteins/365)/(population*1000)] standData[,fatSupplyQt_gCd:=(Fats/365)/(population*1000)] standData[,Calories:=(Calories/1000000)] standData[,Proteins:=(Proteins/1000000)] standData[,Fats:=(Fats/1000000)] return(standData) } <file_sep>/R/suaFilling_NW.R ##' This function replaces the old BalanceResidual ##' ##' This function forces a the filling of empty elements in the pulled SUA ##' by allocating the "imbalance" according to a Ranking of the possible ##' Uitlizazions for each combination of country/commodity. ##' ##' 1. PRODUCTION OF DERIVERD ##' Production of derived commodities is created, when is not estimated via the ##' sub-module of derived and when utilization are higher than supplies. ##' ##' 2. FOOD PROCESSING ##' with all productions, food processing is created for all parent commoditeis ##' ##' 3. ALL OTHER ELEMENTS ARE FILLED, IF NEEDED ##' - if supply > utilization a Multiple filler approach is used: ##' * If all the ranked utilizations are present ##' these are proportionally incremented ##' * if one is empty, imbalance goes to this commodity ##' * if more than one is empty, Utilization are created based on a ranking of possible Utilization ##' coming from an external source. ##' The approach used id the "Inverse Ranking Rule" ##' ##' - If supply < utilization ##' * All utilization are reduced by 30% ##' * if this is not enought to cover the imbalance, production is incremented if is not official, ##' if is official, utilization are firs reduced of another 30% and then production is reduced. ##' ##' If OFFICIAL PRODUCTION is CHANGED, changed rows go in an external file ##' ##' Trade is never touched ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param p The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param primaryCommodities Primary level commodities (such as wheat, oranges, ##' sweet potatoes, etc.) should not be balanced at this step but rather by ##' the balancing algorithm. This argument allows the user to specify a ##' character vector with these primary element codes. ##' @param stockCommodities This list specify if the commodity can be allocated to stock ##' @param utilizationTable is the external utilizataion table ##' @param imbalanceThreshold The size that the imbalance must be in order for ##' an adjustment to be made. ##' @param cut these are primary equivalent commodities. ##' @param tree this is the sub tree used in the function. ##' @param loop1 insicates if is the firs or second loop before or after the food Proc calculation ##' @return the Value column of the passed data.table is updated ##' suaFilling_NW = function(data, p = p, tree=tree, primaryCommodities = c(), stockCommodities = c(), debugFile= NULL, utilizationTable=c(), imbalanceThreshold = 10,loop1=TRUE){ # The commodities that have to be crude balanced are the NON PRIMARY data$Protected[is.na(data$Protected)] = FALSE data$Official[is.na(data$Official)] = FALSE data$ProtectedProd[data$food_classification=="Food"] = TRUE data$ProtectedProd[data$type=="CRPR"] = TRUE data$Protected[data$food_classification=="Food"&data$measuredElementSuaFbs=="production"] = TRUE data$Protected[data$type=="CRPR"&data$measuredElementSuaFbs=="production"] = TRUE stopifnot(imbalanceThreshold > 0) eleToExcludeS = c(p$productionCode,p$exportCode,p$importCode,p$stockCode,p$foodProcCode) eleToExclude = c(p$productionCode,p$exportCode,p$importCode,p$foodProcCode,p$wasteCode) ############################# # STEP 1: create production for subsequent food processing calculation: ############################# ## Supply-Utilization = imbalance data[, imbalance := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, NA))))))))))))), by = c(p$mergeKey)] # we need the sum of Utilizations data[, sumUtils := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 0, ifelse(get(p$elementVar) == p$importCode, 0, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode, ifelse(is.na(Value),0,ifelse(Value<0,0,1)), ifelse(get(p$elementVar) == p$foodCode, 1, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 1, ifelse(get(p$elementVar) == p$wasteCode, 1, ifelse(get(p$elementVar) == p$seedCode, 1, ifelse(get(p$elementVar) == p$industrialCode, 1, ifelse(get(p$elementVar) == p$touristCode, 1, ifelse(get(p$elementVar) == p$residualCode, 1, NA))))))))))))), by = c(p$mergeKey)] data[, sumSup := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode, 0, ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, NA))))))))))))), by = c(p$mergeKey)] data[, sumSupstock := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode,ifelse(is.na(Value),0,ifelse(Value<0,-1,0)), ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, NA))))))))))))), by = c(p$mergeKey)] # the following line added otherwise some cases were not treated at all data[is.na(ProtectedProd),ProtectedProd:="FALSE"] data[is.na(ProtectedFood),ProtectedFood:="FALSE"] # I serparate the different blocks of data for trating them separately dataPrimary = data[(get(p$itemVar) %in% primaryCommodities)] dataNoImbP = dataPrimary[imbalance<=imbalanceThreshold&imbalance>=(-imbalanceThreshold)] # never touched dataNegImbP = dataPrimary[imbalance < (-imbalanceThreshold)] dataPosImbP = dataPrimary[imbalance > imbalanceThreshold] dataNoPrimary = data[!(get(p$itemVar) %in% primaryCommodities)] dataNoImb = dataNoPrimary[imbalance<=imbalanceThreshold&imbalance>=(-imbalanceThreshold)] # never touched dataNegImb = dataNoPrimary[imbalance < (-imbalanceThreshold)] dataPosImb = dataNoPrimary[imbalance > imbalanceThreshold] ########################## Supply < utilization (= imbalance < -imbalanceThreshold) if (loop1==TRUE) { # # # if production EXISTS (protected or estimated Via the sub-module), # # # DON'T DO ANYTHING. # # if production do NOT EXISTS or is a NOT protected 0, create it # dataNegImb[get(p$elementVar)==p$productionCode & ProtectedProd==FALSE & (is.na(Value)|Value==0), # newValue:=ifelse(is.na(Value),-imbalance,Value-imbalance)] #----------------------# # This is being changed the 12/04/2018 as per Salar request # create OR increase production any time is not sufficient to cover Import-Export # dataNegImb[get(p$elementVar)==p$productionCode & ProtectedProd==FALSE, # newValue:=ifelse(is.na(Value),-imbalance,Value-imbalance)] if("newValue" %in% colnames(dataPosImbP)){ dataPosImbP[!is.na(newValue)&!Protected==TRUE,Value:=newValue] # dataPosImbP[,newValue:=NULL] dataPosImbP=dataPosImbP[,1:20,with=FALSE] } else{dataPosImbP$newValue=NA} if("newValue" %in% colnames(dataNegImb)){ dataNegImb[!is.na(newValue)&!Protected==TRUE,Value:=newValue] # dataPosImbP[,newValue:=NULL] dataNegImb=dataNegImb[,1:20,with=FALSE] } else{dataNegImb$newValue=NA} if("newValue" %in% colnames(dataPosImb)){ dataPosImb[!is.na(newValue)&!Protected==TRUE,Value:=newValue] # dataPosImbP[,newValue:=NULL] dataPosImb=dataPosImb[,1:20,with=FALSE] } else{dataPosImb$newValue=NA} if(!("newValue" %in% colnames(dataNoImbP))){dataNoImbP$newValue=NA} if(!("newValue" %in% colnames(dataNegImbP))){dataNegImbP$newValue=NA} if(!("newValue" %in% colnames(dataNoImb))){dataNoImb$newValue=NA} data=rbind(dataNoImbP,dataNegImbP,dataNoImb,dataPosImbP,dataNegImb,dataPosImb) data$newValue[is.na(data$newValue)] = data$Value[is.na(data$newValue)] } ### This refers only to the FIrst LOOP if (loop1==FALSE) { ######################### NEW VERSION 12/06/2017 ######################### DEFINITIONS # First of all try to reduce UTilizations without tuching Food pTolerance = 0.3 # 1. reduce the present Utilizations # by the 30% of each utilization # stock here are incremented or reduced of an amount proportional # to their value in respect to other utilization ############## ##############SUMEDA#################### ########## # Comment 1: The statement above does not correspond to the code. All the utilization are reduced by 30%. # if the reduction of maximum 30% is enought to cover all imbalance dataNegImb_ptol=rbind(dataNegImb[abs(imbalance)<=(pTolerance*sumUtils)], dataNegImbP[abs(imbalance)<=(pTolerance*sumUtils)]) # dataNegImb_ptol=dataNegImb[abs(imbalance)<=(pTolerance*sumUtils)] dataNegImb_ptol[,newValue:= ifelse(is.na(Value),NA, ifelse(get(p$elementVar)%in%eleToExclude,NA, Value-abs(Value)*(abs(imbalance)/(sumUtils+(sumSupstock-sumSup)))))] # if the all imbalance is NOT covered by the 30% of the all utilization # reduce the utilizations by 30% anyway dataNegImb_Noptol=rbind(dataNegImb[ # Production existing (either officiali or not) abs(imbalance)>(pTolerance*sumUtils)], dataNegImbP[ # Production existing (either officiali or not) abs(imbalance)>(pTolerance*sumUtils)]) # dataNegImb_Noptol=dataNegImb[ # Production existing (either officiali or not) # abs(imbalance)>(pTolerance*sumUtils)] # dataNegImb_Noptol[,newValue:= ifelse(is.na(Value),NA, ifelse(get(p$elementVar)%in%eleToExclude,NA, Value-(pTolerance*(Value))))] # NW only change non-official data dataNegImb_ptol[,Value:=ifelse(!is.na(newValue)&!Protected==TRUE,newValue,Value)] #dataNegImb_ptol[,newValue:=NULL] dataNegImb_Noptol[,Value:=ifelse(!is.na(newValue)&!Protected==TRUE,newValue,Value)] #dataNegImb_Noptol[,newValue:=NULL] # The sum of the difference is then distributed to stockchange and industrial use dataNegImbAll=rbind(dataNegImb_ptol,dataNegImb_Noptol) dataNegImbComm=dataNegImbAll[,measuredItemSuaFbs] # dataNegImb=rbind(dataNegImb_ptol,dataNegImb_Noptol) # dataNegImbComm=dataNegImb[,measuredItemSuaFbs] ############################################################################################ ############################################################################################ ############################################################################################ ############################################################################################ # Now recalculate all steps for updating those commodities that have been balanced # First reconstruct the data if(!("newValue" %in% colnames(data))){data$newValue=NA} data=data[!(measuredItemSuaFbs%in%dataNegImbComm)] data=rbind(data,dataNegImbAll) # Then start again ## Supply-Utilization = imbalance data[, imbalance := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, NA))))))))))))), by = c(p$mergeKey)] # we need the sum of Utilizations data[, sumUtils := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 0, ifelse(get(p$elementVar) == p$importCode, 0, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode, ifelse(is.na(Value),0,ifelse(Value<0,0,1)), ifelse(get(p$elementVar) == p$foodCode, 1, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 1, ifelse(get(p$elementVar) == p$wasteCode, 1, ifelse(get(p$elementVar) == p$seedCode, 1, ifelse(get(p$elementVar) == p$industrialCode, 1, ifelse(get(p$elementVar) == p$touristCode, 1, ifelse(get(p$elementVar) == p$residualCode, 1, NA))))))))))))), by = c(p$mergeKey)] data[, sumSup := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode, 0, ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, NA))))))))))))), by = c(p$mergeKey)] data[, sumSupstock := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, 0, ifelse(get(p$elementVar) == p$stockCode,ifelse(is.na(Value),0,ifelse(Value<0,-1,0)), ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, NA))))))))))))), by = c(p$mergeKey)] # the following line added otherwise some cases were not treated at all data[is.na(ProtectedProd),ProtectedProd:="FALSE"] data[is.na(ProtectedFood),ProtectedFood:="FALSE"] # I serparate the different blocks of data for trating them separately dataPrimary = data[(get(p$itemVar) %in% primaryCommodities)] dataNoImbP = dataPrimary[imbalance <= imbalanceThreshold&imbalance>=(-imbalanceThreshold)] # never touched dataNegImbP = dataPrimary[imbalance < (-imbalanceThreshold)] # never touched dataPosImbP = dataPrimary[imbalance > imbalanceThreshold] dataNoPrimary = data[!(get(p$itemVar) %in% primaryCommodities)] dataNoImb = dataNoPrimary[imbalance <= imbalanceThreshold&imbalance>=(-imbalanceThreshold)] # never touched dataNegImb = dataNoPrimary[imbalance < (-imbalanceThreshold)] dataPosImb = dataNoPrimary[imbalance > imbalanceThreshold] dataPosImbAll = rbind(dataPosImb,dataPosImbP) ########################## Supply < utilization (= imbalance < -imbalanceThreshold) # if production is not official, create production dataNegImb[ProtectedProd=="FALSE" & get(p$elementVar)==p$productionCode&(!(type=="CRPR"))&Protected==FALSE, newValue:=ifelse(is.na(Value),-imbalance,Value-imbalance)] ########################## ######################################################## # if production is official pTolerance = 0.3 dataNegImbOffP = dataNegImb[ProtectedProd=="TRUE"] # 1. Try to reduce the present Utilizations # only if at least the 70% of each utilization remains # stock here are incremented or reduced of an amount proportional # to their value in respect to other utilization dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)<=(pTolerance*sumUtils), newValue:= ifelse(is.na(Value),NA, ifelse(get(p$elementVar)%in%eleToExclude,NA, Value-abs(Value)*(abs(imbalance)/(sumUtils+(sumSupstock-sumSup)))))] # 2. If Imbalance is too high # save this data outside NoFillable=dataNegImbOffP[(abs(imbalance)>(pTolerance*sumUtils))] # & force the reduction of utilization (up to 30% of their value) & increase production dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)>(pTolerance*sumUtils)&sumUtils>0, newValue:= ifelse(get(p$elementVar)%in%eleToExclude[-which(eleToExclude=="production")],NA, ifelse(get(p$elementVar)==p$productionCode,(ifelse(is.na(Value),0,Value)+abs(imbalance)-pTolerance*sumUtils), ifelse(is.na(Value),NA,Value-(abs(Value)/(sumUtils+(sumSupstock-sumSup))) *(sumUtils*pTolerance))))] # & force production always (not just if SumUtils==0) # dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)>(pTolerance*sumUtils)&sumUtils==0, #Comment by SUMEDA ===== here the condition SumUtils==0 is missing. Therefore, it is overwriting the production values computed in the above step no matter the condition # sumUtils>0 or sumUtils ==0. To check!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)>(pTolerance*sumUtils), newValue:=ifelse(get(p$elementVar)==p$productionCode, ifelse(is.na(Value),0,Value)+abs(imbalance),NA)] # ######################################################## ## Supply > utilization (= imbalance > imbalanceThreshold) ### Loop for Non Primary and primary commodity has been unified here (04/08/2018) # actualCommodities = dataPosImb[,unique(measuredItemSuaFbs)] actualCommodities = dataPosImbAll[,unique(measuredItemSuaFbs)] # cristina <- copy(dataPosImbAll) for (i in actualCommodities){ # If none of the utilization is activable based in the utilization Table if(length(dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank),Value])==0){ # CRISTINA change made august 2018 # Save these data outside and send them for manual check and adjustment # (before everything was send conventionally on food) # dataPosImbAll[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode))& # get(p$elementVar)==p$foodCode& # food_classification=="Food"& # !Protected==TRUE,Value:=Value+imbalance] NoBalanced = dataPosImbAll[measuredItemSuaFbs==i] setnames(NoBalanced, "measuredItemSuaFbs", "measuredItemFbsSua") standData = NoBalanced standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standData <- standData[!is.na(Value),] standData[, flagObservationStatus := "I"] standData[, flagMethod := "x"] if(!is.null(debugFile)){ saveFBSItermediateStep(directory=paste0(basedir,"/debugFile/Batch_",batchnumber), fileName=paste0("B",batchnumber,"_04_NotBalancedDerived"), data=standData) } }else{ # Se tutti i Value sono popolati ################################################################################################ SUMEDA####################################################### #####SUMEDA : Previouse version # if(length(dataPosImbAll[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) # &!is.na(rank)&(is.na(Value)),Value])==0){ ###############################################################SUMEDAA########################################################### if(length(dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank)&(is.na(Value)),Value])==0){ # distribuisci inbalance proporzionalmente ai value stessi (considerando anche quelli che non hanno # eventualmente ranking) # e diminuendo lo stock negativo, se presente # sumV=sum(dataPosImb[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # # &!is.na(rank) # &Value>0,Value],na.rm=TRUE) # #Sumeda: if the commodity is not stockable, the imbalance is distributed to all utilizations including also stock if (!(i %in% unique(Stock_Items$cpc_code))){###SUMEDA dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank) ############### change 5/15/2018 #cristina version without the condition &Value!=0, newValue:=ifelse(is.na(Value),NA, Value+Value*(imbalance/(sumUtils+(sumSupstock-sumSup))))] }else {#Sumeda::: if the commodity is stockable, it arises two senarios. 1. the stock figure is zero and 2. the stock figure is non-zero if (dim(dataPosImbAll[measuredItemSuaFbs==i #sumeda &(get(p$elementVar)%in%c(p$stockCode)) & Value !=0 & !is.na(Value)])[1] != 0){#Sumeda :: if the stock figure is non zero, it will follow the above method to allocate the imbalance dataPosImbAll[measuredItemSuaFbs==i #sumeda &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank) & Value!=0, newValue:=ifelse(is.na(Value),NA, Value+Value*(imbalance/(sumUtils+(sumSupstock-sumSup))))] }else {#sumeda :: if the stock figure is zero, it is useless to have a proportion since stock is zero. So what I did is, I allocate all the imbalance to stock. dataPosImbAll[measuredElementSuaFbs == "stockChange" & is.na(Value), Value := 0] dataPosImbAll[measuredItemSuaFbs==i & measuredElementSuaFbs == "stockChange" &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank) , newValue:= Value + imbalance] } } }else{ #se un valore non 'e popolato e non 'e stock if(length(dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank)&(is.na(Value)|Value==0),Value])==1){ # metti tutto l' imbalance in questo elemento dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode))&!is.na(rank) &(is.na(Value)|Value==0), newValue:=imbalance] }else{ # se c'e piu' di un elemento non popolato if(length(dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank)&(is.na(Value)|Value==0),Value])>1){ # allora in base alla seguente funzione dei rank e rank inversi: NON PIU' # allora assegna il valore in base alla percentuale sumPercent = sum(dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank)&(is.na(Value)|Value==0),percent]) dataPosImbAll[measuredItemSuaFbs==i &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) &!is.na(rank)&(is.na(Value)|Value==0),newValue:=imbalance*(percent/sumPercent)] # sumRank = sum(dataPosImb[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),rankInv]) # dataPosImb[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),newValue:=imbalance*(rankInv/sumRank)] } } } } } ############ End loop no primary ############ ### Loop for primary # 04/08/2018 all the following part has been deleted because primaries with positive imbalanec are now balanced # # # the loop is reduced to the commodities for which Food is NOT PROTECTED # actualCommoditiesP = dataPosImbP[measuredElementSuaFbs=="food"&ProtectedFood=="FALSE",unique(measuredItemSuaFbs)] # # actualCommoditiesP = dataPosImbP[,unique(measuredItemSuaFbs)] # # for (i in actualCommoditiesP){ # # If none of the utilization is activable based in the utilization Table # if(length(dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) # &!is.na(rank),Value])==0){ # # conventionally put all on food (As was in the previous version of the new module) # # this a very rare case but can happen # # ONLY IF FOOD IS NOT PROTECTED # # if(dataPosImbP[measuredItemSuaFbs==i # # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode))& # # get(p$elementVar)==p$foodCode,ProtectedFood]=="FALSE"){ # # dataPosImbP[measuredItemSuaFbs==i # # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode))& # # get(p$elementVar)==p$foodCode,newValue:=imbalance] # # } # IF FOOD IS PROTECTED THE LINE WILL REMAIN IMBALANCED # }else{ # # # Se tutti i Value sono popolati # if(length(dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)),Value])==0){ # # AS NOW WE ARE CONSIDERING PRIMARIES, IF ALL THE VALUES ARE POPULATED # # DON'T DO ANYTHING # dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # # &!is.na(rank) # &Value>0, # newValue:=Value] # }else{ # #se un valore non 'e popolato e non e' stock ED E' FOOD # if(length(dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode)) # &!is.na(rank)&(is.na(Value)|Value==0),Value])==1){ # # metti tutto l'imbalance in questo elemento # # ONLY IF IS FOOD # # what we are tring to do is not to necessary balance primary, but only create food # # if this should be there and is not # dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%c(eleToExclude,p$stockCode))&!is.na(rank) # &(is.na(Value)|Value==0) # &get(p$elementVar)==p$foodCode&ProtectedFood=="FALSE", # newValue:=imbalance] # # }else{ # # se c'e piu' di un elemento non popolato e food é fra questi elementi # if(length(dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),Value])>1 # &(p$foodCode %in% dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),get(p$elementVar)]) # ){ # # allora in base alla seguente funzione dei rank e rank inversi: # sumRank = sum(dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),rankInv]) # dataPosImbP[measuredItemSuaFbs==i # &!(get(p$elementVar)%in%eleToExclude) # &!is.na(rank)&(is.na(Value)|Value==0),newValue:=imbalance*(rankInv/sumRank)] # } # } # } # # } # # } # ############ End loop primary ### ### ### ### ### EXTERNAL SAVING OF FORCED INFORMATION if(dim(dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)>(pTolerance*sumUtils)])[1]>0){ NoFillable= dataNegImb[ProtectedProd=="TRUE"&abs(imbalance)>(pTolerance*sumUtils)] if("newValue" %in% colnames(NoFillable)){ NoFillable[!is.na(newValue)&!Protected==TRUE,Value:=newValue] NoFillable=NoFillable[,c(3,2,1,4,5,6,7,17,20),with=FALSE] } setnames(NoFillable, "measuredItemSuaFbs", "measuredItemFbsSua") standData = NoFillable standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,newValue)] standData_Intermediate=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standData <- standData[!is.na(Value),] standData[, flagObservationStatus := "I"] standData[, flagMethod := "x"] if(!is.null(debugFile)){ saveFBSItermediateStep(directory=paste0(basedir,"/debugFile/Batch_",batchnumber), fileName=paste0("B",batchnumber,"_10_ForcedProduction"), data=standData_Intermediate) } } # if("newValue" %in% colnames(dataPosImbP)){ # dataPosImbP[!is.na(newValue),Value:=newValue] # # dataPosImbP[,newValue:=NULL] # dataPosImbP=dataPosImbP[,1:17,with=FALSE] # } if("newValue" %in% colnames(dataNegImb)){ dataNegImb[!is.na(newValue)&!Protected==TRUE,Value:=newValue] # dataPosImbP[,newValue:=NULL] dataNegImb=dataNegImb[,1:20,with=FALSE] }else{dataNegImb$newValue=NA} if("newValue" %in% colnames(dataPosImbAll)){ dataPosImbAll[!is.na(newValue)&!Protected==TRUE,Value:=newValue] dataPosImbAll=dataPosImbAll[,1:20,with=FALSE] }else{dataPosImbAll$newValue=NA} # data=rbind(dataNoImbP,dataNegImbP,dataNoImb,dataPosImbP,dataNedatagImb,dataPosImb) data=dplyr::bind_rows(dataNoImbP,dataNegImbP,dataNoImb,dataNegImb,dataPosImbAll) data = as.data.table(data) } #this brackets refer only at the second loop data[, c("imbalance","sumUtils","sumSup") := NULL] } <file_sep>/tests/testthat.R library(testthat) library(faoswsStandardization) test_check("faoswsStandardization") <file_sep>/modules/aggregateSuaBal/main.R ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to aggregate des figures at SUA balanced level ##' ##' ##' **Inputs:** ##' ##' * sua balanced ##' ##'' **Output:** ##' ##' * csv file attached in mail ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) library(faoswsStandardization) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/aggregateSuaBal/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) startYear = as.numeric(2010) #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2017) #geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # # ##Select the countries based on the user input parameter selectedGEOCode =sessionCountries ######################################### ##### Pull from SUA balanced data ##### ######################################### message("Pulling SUA balanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredElementSuaFbs") eleKeys <-eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_balanced_data = GetData(key) # kcalData <- subset(sua_balanced_data, measuredElementSuaFbs %in% c("664")) kcalData[,6:7]<-NULL kcalData<-kcalData %>% group_by(geographicAreaM49,timePointYears) %>% dplyr::mutate(totDES=sum(Value,na.rm = T)) kcalData2 = melt.data.table(setDT(kcalData),id.vars = c("geographicAreaM49","measuredItemFbsSua","timePointYears"), measure.vars = c("Value","totDES")) setnames(kcalData2, "variable", "Aggregation") setnames(kcalData2, "value", "Value") kcalData2[,Aggregation:=ifelse(Aggregation=="Value","Item","GRAND TOTAL")] grandTotal=subset(kcalData2,Aggregation=="GRAND TOTAL") grandTotal[,measuredItemFbsSua:="S2901"] grandTotal=unique(grandTotal) grandTotal=nameData("suafbs","fbs_balanced_",grandTotal) items=nameData("suafbs","sua_balanced",subset(kcalData2,Aggregation=="Item")) kcalDataWide = dcast.data.table(setDT(items),geographicAreaM49+geographicAreaM49_description+ measuredItemFbsSua+measuredItemFbsSua_description~timePointYears , fun.aggregate = NULL,value.var = "Value") GTWide = dcast.data.table(setDT(grandTotal),geographicAreaM49+geographicAreaM49_description+ measuredItemFbsSua+measuredItemFbsSua_description~timePointYears , fun.aggregate = NULL,value.var = "Value") toSend=rbind(GTWide,kcalDataWide) bodySuaBALAggregation= paste("The Email contains the aggregated caloric intake at sua balanced level", sep='\n') sendMailAttachment(toSend,"SuaBalAggregation",bodySuaBALAggregation) ############ calculate imbalance commDef=ReadDatatable("fbs_commodity_definitions") # primaryProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | primary_commodity=="X"]] # primary=commDef$cpc[commDef[,primary_commodity=="X"]] # # # proxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | derived=="X"]] food=commDef$cpc[commDef[,food_item=="X"]] sua_balanced_data[, imbalance := sum(ifelse(is.na(Value), 0, as.numeric(Value)) * ifelse(measuredElementSuaFbs == "5510", 1, ifelse(measuredElementSuaFbs == "5610", 1, ifelse(measuredElementSuaFbs == "5910", -1, ifelse(measuredElementSuaFbs == "5071", -1, ifelse(measuredElementSuaFbs == "5141", -1, ifelse(measuredElementSuaFbs == "5023", -1, ifelse(measuredElementSuaFbs == "5520", -1, ifelse(measuredElementSuaFbs == "5016", -1, ifelse(measuredElementSuaFbs == "5525", -1, ifelse(measuredElementSuaFbs == "5165", -1, ifelse(measuredElementSuaFbs == "5164", -1, ifelse(measuredElementSuaFbs == "5166", -1,0))))))))))))), by =c("geographicAreaM49","measuredItemFbsSua", "timePointYears") ] sua_balanced_data[, perc.imbalance := 100*abs(imbalance)/sum(ifelse(is.na(Value), 0, as.numeric(Value)) * ifelse(measuredElementSuaFbs == 5510, 1, ifelse(measuredElementSuaFbs == 5610, 1, ifelse(measuredElementSuaFbs == 5910, -1, ifelse(measuredElementSuaFbs == 5071, -1, ifelse(measuredElementSuaFbs == 5141, 0, ifelse(measuredElementSuaFbs == 5023, 0, ifelse(measuredElementSuaFbs == 5520, 0, ifelse(measuredElementSuaFbs == 5016, 0, ifelse(measuredElementSuaFbs == 5525, 0, ifelse(measuredElementSuaFbs == 5165, 0, ifelse(measuredElementSuaFbs == 5164, 0, ifelse(measuredElementSuaFbs == 5166, 0,0))))))))))))), by =c("geographicAreaM49","measuredItemFbsSua", "timePointYears") ] imbToSend=subset(sua_balanced_data,measuredItemFbsSua %in% food & timePointYears>=2014 & abs(imbalance)>100 & abs(perc.imbalance)>1) imbToSend=unique(imbToSend, incomparables=FALSE, fromLast=FALSE, by=c("geographicAreaM49","measuredItemFbsSua","timePointYears","imbalance")) imbToSend$measuredElementSuaFbs<-NULL imbToSend$Value<-NULL imbToSend$flagObservationStatus<-NULL imbToSend$flagMethod<-NULL data.table::setorder(imbToSend,-perc.imbalance) imbToSend=nameData("suafbs","sua_balanced",imbToSend) bodyImbalances= paste("The Email contains the list of imbalanced food items at SUA bal level. Please check them.", sep='\n') sendMailAttachment(setDT(imbToSend),"ImbalanceList",bodyImbalances) #### FBS AGGREGATES AT SUA LEVEL (NO STANDARDIZATION INVOLVED HERE) fbsTree<-ReadDatatable("fbs_tree") fbsCodes<-GetCodeList(domain = "suafbs", dataset = "fbs_balanced_", "measuredItemFbsSua") fbsCodes=subset(fbsCodes,grepl("^S",code)) fbsCodes=subset(fbsCodes,grepl("[[:upper:]]\\s",description)) fbsCodes$code<-gsub("^S","",fbsCodes$code) # fbsTree <- merge(fbsTree,fbsCodes,by.x = "id1",by.y = "code") ######### kcalData <- subset(sua_balanced_data, measuredElementSuaFbs %in% c("664")) kcalData[,6:7]<-NULL # # kcalData <- merge(kcalData,fbsTree,by.x = "measuredItemFbsSua",by.y = "item_sua_fbs") # # totalDes=kcalData_id[,totDES:=sum(Value, na.rm = T), by=c("geographicAreaM49,timePointYears,id1")] # # #kcalData<-kcalData[,totDES:=sum(Value, na.rm = T), by=c("geographicAreaM49,timePointYears,id1")] agg4=kcalData[,desAgg4:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id4")] agg3=kcalData[,desAgg3:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id3")] agg2=kcalData[,desAgg2:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id2")] agg1=kcalData[,desAgg1:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id1")] agg4=agg4[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id4","desAgg4"),with=F] agg3=agg3[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id3","desAgg3"),with=F] agg2=agg2[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id2","desAgg2"),with=F] agg1=agg1[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id1","desAgg1"),with=F] agg4[,measuredItemFbsSua:=id4] agg4[,id4:=NULL] setnames(agg4,"desAgg4","Value") agg4=unique(agg4) agg3[,measuredItemFbsSua:=id3] agg3[,id3:=NULL] setnames(agg3,"desAgg3","Value") agg3=unique(agg3) agg2[,measuredItemFbsSua:=id2] agg2[,id2:=NULL] setnames(agg2,"desAgg2","Value") agg2=unique(agg2) agg1[,measuredItemFbsSua:=id1] agg1[,id1:=NULL] setnames(agg1,"desAgg1","Value") agg1=unique(agg1) aggData=rbind(agg1,agg2,agg3,agg4) aggData[,Value:=round(Value,0)] aggDataWide = dcast.data.table(setDT(aggData),geographicAreaM49+ measuredItemFbsSua ~timePointYears , fun.aggregate = NULL,value.var = "Value") aggDataWide$measuredItemFbsSua<-gsub("^2","S2",aggDataWide$measuredItemFbsSua) aggDataWide<-nameData("suafbs","fbs_balanced_",aggDataWide) bodyImbalances= paste("The Email contains the FBS aggregates by DES calculated at SUA BALANCED LEVEL.", sep='\n') sendMailAttachment(setDT(aggDataWide),"FbsAggAtSUA",bodyImbalances) <file_sep>/modules/printTree/main.R ## load the library library(faosws) library(faoswsUtil) library(faoswsBalancing) library(faoswsStandardization) library(faoswsFlag) message("libraries loaded") library(data.table) library(igraph) library(stringr) library(dplyr) # library(dtplyr) library(MASS) library(lattice) library(reshape2) library(sendmailR) library(knitr) if(packageVersion("faoswsStandardization") < package_version('0.1.0')){ stop("faoswsStandardization is out of date") } ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { library(faoswsModules) message("Not on server, so setting up environment...") # Read settings file sws.yml in working directory. See # sws.yml.example for more information PARAMS <- ReadSettings("modules/printTree/sws.yml") message("Connecting to server: ", PARAMS[["current"]]) R_SWS_SHARE_PATH = PARAMS[["share"]] apiDirectory = "./R" ## Get SWS Parameters SetClientFiles(dir = PARAMS[["certdir"]]) GetTestEnvironment( baseUrl = PARAMS[["server"]], token = PARAMS[["token"]] ) batchnumber = 000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT } else { batchnumber = 000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT message("Running on server, no need to call GetTestEnvironment...") } #User name is what's after the slash SWS_USER = regmatches(swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE)) # instead of replace the existing # (for example save example files for different batches) # put the name in the .yml file # default is NULL if(CheckDebug()){ SUB_FOLDER = paste0(PARAMS[["subShare"]],batchnumber) } message("Getting parameters/datasets...") # start and end year for standardization come from user parameters startYear = swsContext.computationParams$startYear endYear = swsContext.computationParams$endYear geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = as.character(startYear:endYear) fbsItem = swsContext.computationParams$FBSitem ## Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] # Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) areaKeys = selectedGEOCode ############################################################## ############ DOWNLOAD AND VALIDATE TREE ###################### ############################################################## ptm <- proc.time() tree=getCommodityTreeNewMethod(areaKeys,yearVals) message((proc.time() - ptm)[3]) # validateTree(tree) # NA ExtractionRates are recorded in the sws dataset as 0 # for the standardization, we nee them to be treated as NA # therefore here we are re-changing it tree[Value==0,Value:=NA] ############################################################## ################### MARK OILS COMMODITY ###################### ############################################################## oilFatsCPC=c("2161", "2162", "21631.01", "21641.01", "21641.02", "2168", "21691.14", "2165", "34120", "21932.02", "2166", "21691.07", "2167", "21673", "21691.01", "21691.02", "21691.03", "21691.04", "21691.05", "21691.06", "21631.02", "21691.08", "21691.09", "21691.10", "21691.11", "21691.12", "21691.13", "21691.90", "23620", "21700.01", "21700.02", "21693.02", "34550", "F1275", "21512", "21512.01", "21513", "21514", "F0994", "21515", "21511.01", "21511.02", "21521", "21511.03", "21522", "21519.02", "21519.03", "21529.03", "21529.02", "21932.01", "21523", "F1243", "F0666") tree[(measuredItemParentCPC%in%oilFatsCPC|measuredItemChildCPC%in%oilFatsCPC),oil:=TRUE] ############################################################## ################ CLEAN NOT OFFICIAL SHARES ################### ################ & SHARES EXCEPT OILS ################### ############################################################## ## (E,f) have to be kept ## any other has to ve cleaned except the oils tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] tree[measuredElementSuaFbs=="share"&(checkFlags=="(E,f)"|oil==TRUE),keep:=TRUE] tree[measuredElementSuaFbs=="share"&is.na(keep),Value:=NA] tree[,checkFlags:=NULL] tree[,oil:=NULL] tree[,keep:=NULL] ############################################################## ############ Update params for specific dataset ############## ############################################################## params = defaultStandardizationParameters() params$itemVar = "measuredItemSuaFbs" params$mergeKey[params$mergeKey == "measuredItemCPC"] = "measuredItemSuaFbs" params$elementVar = "measuredElementSuaFbs" params$childVar = "measuredItemChildCPC" params$parentVar = "measuredItemParentCPC" params$productionCode = "production" params$importCode = "imports" params$exportCode = "exports" params$stockCode = "stockChange" params$foodCode = "food" params$feedCode = "feed" params$seedCode = "seed" params$wasteCode = "loss" params$industrialCode = "industrial" params$touristCode = "tourist" params$foodProcCode = "foodManufacturing" params$residualCode = "residual" params$createIntermetiateFile= "TRUE" params$protected = "Protected" params$official = "Official" ############################################################## #################### SET KEYS FOR DATA ####################### ############################################################## elemKeys=c("5510", "5610", "5071", "5023", "5910", "5016", "5165", "5520","5525","5164","5166","5141") desKeys = c("664","674","684") # 5510 Production[t] # 5610 Import Quantity [t] # 5071 Stock Variation [t] # 5023 Export Quantity [t] # 5910 Loss [t] # 5016 Industrial uses [t] # 5165 Feed [t] # 5520 Seed [t] # 5525 Tourist Consumption [t] # 5164 Residual other uses [t] # 5166 Food [t] # 5141 Food Supply (/capita/day) [Kcal] # ##### First of all the session data have to be cleaned # ## CLEAN sua_balanced # if(!CheckDebug()){ # CONFIG <- GetDatasetConfig(swsContext.datasets[[4]]@domain, swsContext.datasets[[4]]@dataset) # # datatoClean=GetData(sessionKey_suabal) # # datatoClean=datatoClean[timePointYears%in%yearVals] # # datatoClean[, Value := NA_real_] # datatoClean[, CONFIG$flags := NA_character_] # # SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) # # # ## CLEAN fbs_standardized # # CONFIG <- GetDatasetConfig(swsContext.datasets[[5]]@domain, swsContext.datasets[[5]]@dataset) # # datatoClean=GetData(sessionKey_fbsStand) # datatoClean=datatoClean[timePointYears%in%yearVals] # # datatoClean[, Value := NA_real_] # datatoClean[, CONFIG$flags := NA_character_] # # SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) # # # # ## CLEAN fbs_balanced # # CONFIG <- GetDatasetConfig(swsContext.datasets[[1]]@domain, swsContext.datasets[[1]]@dataset) # # datatoClean=GetData(sessionKey_fbsBal) # datatoClean=datatoClean[timePointYears%in%yearVals] # # datatoClean[, Value := NA_real_] # datatoClean[, CONFIG$flags := NA_character_] # # SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) # # ### Send Mail for Data Cleaned # # body = paste("Before processing new unbalanced SUAs", # # " ", # # "All Datasets have been cleaned" # # ,sep='\n') # # # # sendmailR::sendmail(from = "<EMAIL>", # # to = swsContext.userEmail, # # subject = sprintf("sessions cleaned"), # # msg = strsplit(body,"\n")[[1]]) # # } ## Starting reading SUAs message("Reading SUA data...") itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = yearVals) )) ############################################################## ########## DOWNLOAD AND FIX DATA FOR SUGAR CODES ############# ############################################################## # load(file.path(PARAMS$localFiles, "dataTESTNewStand.RData")) # data=data[geographicAreaM49=="1248"&timePointYears%in%yearVals] # data=suppressWarnings(dataDownloadFix(key=key,p=params)) data = elementCodesToNames(data = GetData(key), itemCol = "measuredItemFbsSua", elementCol = "measuredElementSuaFbs") message("elementCodesToNames ok") data[measuredElementSuaFbs=="foodmanufacturing",measuredElementSuaFbs:="foodManufacturing"] setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") data[measuredElementSuaFbs=="stock_change",measuredElementSuaFbs:="stockChange"] data[measuredElementSuaFbs=="stock",measuredElementSuaFbs:="stockChange"] data=data[timePointYears%in%yearVals] data=data[!is.na(measuredElementSuaFbs)] ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## ####################################### datas=data[measuredItemSuaFbs %in% c("23511.01","23512","2351f")] datas[,Value2:=sum(Value*ifelse(measuredItemSuaFbs=="2351f",0,1)),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] sugarComb = datas[, .N, by = c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] # Filter all the rows for which only one row exists filterA=sugarComb[N==1] filterA=filterA[,N:=NULL] datasA=datas[filterA, ,on=c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] # check if some of this rows are not 2351f and change the flag, in that case datasA[measuredItemSuaFbs!="2351f",flagObservationStatus:=ifelse(flagObservationStatus!="I","I",flagObservationStatus)] datasA[measuredItemSuaFbs!="2351f",flagMethod:=ifelse(!(flagMethod%in%c("e","s")),"s",flagMethod)] datasA[,measuredItemSuaFbs:="2351f"] datasA[,Value2:=NULL] filterB=sugarComb[N>1] filterB=filterB[,N:=NULL] datasC=datas[filterB, ,on=c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] datasC[,s2351f:=max(Value2,Value),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] datasC[,c("Value","Value2"):=NULL] datasC[,Value:=s2351f*ifelse(measuredItemSuaFbs=="2351f",1,0),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] datasB=datasC[Value!=0] sugarComb2=datasB[,.N,by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")][,N:=NULL] datasD=datasC[sugarComb2,,on=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] datasD=setdiff(datasC,datasD) datasD[,Value:=sum(s2351f*ifelse(measuredItemSuaFbs=="2351f",0,1)),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] datasD=unique(datasD,by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")) datasD[,measuredItemSuaFbs:="2351f"] datasB=datasB[,colnames(datasA),with=FALSE] datasD=datasD[,colnames(datasA),with=FALSE] dataTorBind=rbind(datasA,datasB,datasD) data=data[!(measuredItemSuaFbs %in% c("23511.01","23512","2351f"))] data=rbind(data,dataTorBind) # ######################################## # # data=data[, list(Value = sum(Value, na.rm = TRUE)), # by = c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","flagObservationStatus","flagMethod")] data=left_join(data,flagValidTable,by=c("flagObservationStatus","flagMethod"))%>% data.table data[flagObservationStatus%in%c("","T"),Official:=TRUE] # data[flagObservationStatus%in%c(""),Official:=TRUE] data[is.na(Official),Official:=FALSE] # data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Protected","Official"))] # ######### ######### ######### ####################################### dataFlags = copy(data) ############################################################## # #protected data # #### CRISTINA: after havig discovered that for crops , official food values are Wrong and have to be deleted. # # now we have to delete all the wrong values: # # THE FOLLOWING STEPS HAVE BEEN COMMENTED BECAUSE THEY SHOULD NOT BE NEEDED # # the data might have to be corrected from the questionnaires # # cropsOfficialFood = c("0111","0112","0113","0115","0116","0117","01199.02","01801","01802") # data[!geographicAreaM49%in%c("604")&get(params$itemVar)%in%cropsOfficialFood # &get(params$elementVar)==params$foodCode # ,Value:=NA] # # only for Japan, delete also Food of Rice Milled. # data[geographicAreaM49=="392"&get(params$elementVar)==params$foodCode&get(params$itemVar)=="23161.02",Value:=0] # ######################### # For DERIVED select only the protected and the estimation (coming from the submodule) message("data chenged ok") level = findProcessingLevel(tree, from = params$parentVar, to = params$childVar, aupusParam = params) primaryEl = level[processingLevel == 0, get(params$itemVar)] # I have to select Protected and Estimation (I,e) # For all the others delete the production value # this will leave the Sua Filling creting prodcution, where needed data[!(get(params$protected)=="TRUE"|(flagObservationStatus=="I"&flagMethod=="e")) &get(params$elementVar)==params$productionCode &!(get(params$itemVar) %in% primaryEl),Value:=NA] ############################################################## ################## RECALCULATE SHARE ##################### ########## FOR COMMODITIES MANUALLY ENTERED ############## ############################################################## p=params ### Compute availability and SHARE data[, availability := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, 0, ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, 0))))))))))))), by = c(p$mergeKey)] mergeToTree = data[, list(availability = mean(availability)), by = c(p$itemVar)] setnames(mergeToTree, p$itemVar, p$parentVar) plotTree = copy(tree) tree2=copy(plotTree) tree2shares=tree[measuredElementSuaFbs=="share"] tree2shares[,share:=Value] tree2shares[,c("measuredElementSuaFbs","Value"):=NULL] tree2exRa=tree[measuredElementSuaFbs=="extractionRate"] tree2exRa[,extractionRate:=Value] tree2exRa[,c("measuredElementSuaFbs","Value"):=NULL] tree2=data.table(left_join(tree2shares,tree2exRa[,c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC", "timePointYears","extractionRate"),with=FALSE],by=c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC", "timePointYears"))) tree2=tree2[!is.na(extractionRate)] tree2 = merge(tree2, mergeToTree, by = p$parentVar, all.x = TRUE) #### SHAREs 1 # share are the proportion of availability of each parent # on the total availability by child # Function checkShareValue() checks the validity of the shares, # change wrong values # return a severity table # and the values to be saved back in the session of the TRee tree2[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] tree2[,availability.child:=availability*get(p$extractVar)] tree2[,shareSum:=sum(share),by=c("measuredItemChildCPC", "timePointYears")] # Create eventual Errors HEre for testing the checkshares function uniqueShares2change = tree2[checkFlags=="(E,f)"&(round(shareSum,3)!=1|is.na(shareSum)), .N, by = c("measuredItemChildCPC", "timePointYears")] uniqueShares2change[, N := NULL] tree2[,newShare:=NA] tree2[,severity:=NA] tree2[,message:=NA] tree2[,newShare:=as.numeric(newShare)] tree2[,severity:=as.integer(severity)] tree2[,message:=as.character(message)] tree2change = vector(mode = "list", length = nrow(uniqueShares2change)) for (i in seq_len(nrow(uniqueShares2change))) { filter = uniqueShares2change[i, ] tree2Subset = tree2[filter, , on = c("measuredItemChildCPC", "timePointYears")] tree2change[[i]] = checkShareValue(tree2Subset) } tree2change = rbindlist(tree2change) tree2merge=copy(tree2change) # Before sending it via email, change flags if(dim(tree2merge)[1]>0){ tree2merge[checkFlags!="(E,f)",flagObservationStatus:="I"] tree2merge[checkFlags!="(E,f)",flagMethod:="i"] tree2merge[,c("checkFlags","availability.child","shareSum","availability","extractionRate"):=NULL] } # sendMail4shares(tree2merge) ############################################################## # IF SHARES ARE VALID ( and Tree2change does not exists), The " tree" is the one to use # onwards # nothing has to be done in this case # IF THERE IS A tree2change, after it has been sent, it has to be integrated in the tree # before going on if(dim(tree2merge)[1]>0){ setnames(tree2merge,"share","Value") tree2merge[,c("severity","message"):=NULL] tree2merge[,measuredElementSuaFbs:="share"] setcolorder(tree2merge,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod")) uniquecomb = tree2merge[, .N, by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears")] uniquecomb[,N := NULL] tree=rbind(tree[!uniquecomb, ,on=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears")],tree2merge) } ############################################################## ################ CHANGE TREE SHAPE & SAVE ################### ################ TREE TO BE RE-EXPORTED ################### ############################################################## # This Tree is saved with a different name with all the flags. # From now on Flags will be removed and the tree will be used as usual, but using # eventual manually corrected extraction rates and Shares. # This is done because the tree has been modifyed in a very subsequent moment from the # time the module was created, therefore functions are designed to be used with a structure of the # tree different from the one of the Dataset Commodity tree # is therefore, very important that this order of the things is not changed # tree2beReExported = copy(tree) tree[,c("flagObservationStatus","flagMethod"):=NULL] tree=data.table(dcast(tree,geographicAreaM49 + measuredItemParentCPC + measuredItemChildCPC + timePointYears ~ measuredElementSuaFbs,value.var = "Value")) ############################################################## ################## LAST FIXES ON TREE ##################### ############################################################## tree=tree[!is.na(extractionRate)] tree=tree[!is.na(measuredItemChildCPC)] ############################################################## ############################################################## ############################################################## ####################################################################################### ## Update tree by setting some edges to "F", computing average extraction rates ## when missing, and bringing in extreme extraction rates FPCommodities <- c( "01499.06", "01921.01","0113") # These commodities are forwards processed instead of backwards processed: # code description type # 3: 01499.06 Kapokseed in shell CRNP # 4: 01921.01 Seed cotton, unginned CRPR tree[, target := ifelse(measuredItemParentCPC %in% FPCommodities, "F", "B")] # MERGE the TREE with the item Map fpr future manipulation itemMap = GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemMap = itemMap[, c("code", "type"), with = FALSE] setnames(itemMap, "code", "measuredItemSuaFbs") data = merge(data, itemMap, by = "measuredItemSuaFbs") setnames(itemMap, "measuredItemSuaFbs", "measuredItemParentCPC") tree = merge(tree, itemMap, by = "measuredItemParentCPC") ## Remove missing elements data = data[!is.na(measuredElementSuaFbs), ] data=data[,c("measuredItemSuaFbs", "measuredElementSuaFbs", "geographicAreaM49", "timePointYears", "Value", "flagObservationStatus", "flagMethod", "Valid", "Protected", "Official", "type"),with=FALSE] ####################################################### # save the initial data locally for future reports if(CheckDebug()){ dir.create(paste0(PARAMS$debugFolder,"/Batch_",batchnumber), showWarnings = FALSE,recursive=TRUE) } if(CheckDebug()){ initialSua = data save(initialSua,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_01_InitialSua_BeforeCB.RData")) } ####################################################### data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type","flagObservationStatus","flagMethod"))] # data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type"))] ############################################################# ########## LOAD NUTRIENT DATA AND CORRECT ############# ############################################################# message("Loading nutrient data...") itemKeys = GetCodeList("agriculture", "aupus_ratio", "measuredItemCPC")[, code] # Nutrients are: # 1001 Calories # 1003 Proteins # 1005 Fats nutrientCodes = c("1001", "1003", "1005") nutrientData = getNutritiveFactors(measuredElement = nutrientCodes, timePointYears = yearVals) setnames(nutrientData, c("measuredItemCPC", "timePointYearsSP"), c("measuredItemSuaFbs", "timePointYears")) # It has been found that some Nutrient Values are wrong in the Nutrient Data Dataset ######### CREAM SWEDEN nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1001",Value:=195] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1003",Value:=3] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1005",Value:=19] ### MILK SWEDEN nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1001",Value:=387] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1003",Value:=26] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1005",Value:=30] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1001",Value:=310] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1003",Value:=23] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1005",Value:=23] # #################################### # ### CRISTINA 08/01/2018 # ### In order to express rice in Milled quivalent, Kcalories of Milled are assigned to Rice paddy. # ### A proportion will later adjust the quantities using Extraction Rates # # milled=nutrientData[measuredItemSuaFbs=="23161.02",Value,by=c("measuredElement","geographicAreaM49","measuredItemSuaFbs")] # milled[,measuredItemSuaFbs:="0113"] # setnames(milled,"Value","ValueMilled") # # nutrientData=merge(nutrientData,milled,by=c("measuredElement","geographicAreaM49","measuredItemSuaFbs"),all = TRUE) # nutrientData[!is.na(ValueMilled),Value:=ValueMilled] # nutrientData[,ValueMilled:=NULL] # #################################### ################################################################# ################################################################# ################################################################# message("Download Utilization Table from SWS...") # utilizationTable=ReadDatatable("utilization_table") utilizationTable=ReadDatatable("utilization_table_percent") utilizationTable=data.table(utilizationTable) # setnames(utilizationTable,colnames(utilizationTable),c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", # "rank", "rankInv")) setnames(utilizationTable,colnames(utilizationTable),c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", "percent","rank", "rankInv")) message("Download zero Weight from SWS...") zeroWeight=ReadDatatable("zero_weight")[,item_code] # zeroWeight=data.table(zeroWeight) message("Download cutItems from SWS...") cutItems=ReadDatatable("cut_items2")[,cpc_code] cutItems=data.table(cutItems) message("Download fbsTree from SWS...") fbsTree=ReadDatatable("fbs_tree") fbsTree=data.table(fbsTree) setnames(fbsTree,colnames(fbsTree),c( "fbsID1", "fbsID2", "fbsID3","fbsID4", "measuredItemSuaFbs")) setcolorder(fbsTree,c("fbsID4", "measuredItemSuaFbs", "fbsID1", "fbsID2", "fbsID3")) message("Defining vectorized standardization function...") standardizationVectorized = function(data, tree, nutrientData,batchnumber, utilizationTable,cutItems,fbsTree){ # record if output is being sunk and at what level sinkNumber <- sink.number() # Prevent sink staying open if function is terminated prematurely (such as # in debugging of functions in standardization) on.exit(while (sink.number() > sinkNumber) sink()) if (nrow(data) == 0) { message("No rows in data, nothing to do") return(data) } # If printCodes is length 0, neither the .md files nor plots are created # If it has a non-zero value, those are the codes which will have file outputs printCodes = character() printCodes = fbsTree[fbsID4==fbsItem,unique(measuredItemSuaFbs)] printCodes=ifelse(length(printCodes)==0,fbsItem,printCodes) printCodes = getChildren(commodityTree = tree, parentColname = params$parentVar, childColname = params$childVar, topNodes = printCodes) if(!CheckDebug()){ basedirPrint = paste0(basedir,"/dataByTree") dir.create(basedirPrint, showWarnings = FALSE,recursive = TRUE) } if(CheckDebug()){ dir.create(paste0(R_SWS_SHARE_PATH, "/", SWS_USER, "/", SUB_FOLDER, "/standardization/") , showWarnings = FALSE,recursive = TRUE ) sink(paste0(R_SWS_SHARE_PATH, "/", SWS_USER,"/", SUB_FOLDER, "/standardization/", data$timePointYears[1], "_", data$geographicAreaM49[1], "_sample_test.md"), split = TRUE) }else{ dir.create(paste0(basedir, "/standardization/") , showWarnings = FALSE,recursive = TRUE ) sink(paste0(basedir,"/standardization/", data$timePointYears[1], "_", data$geographicAreaM49[1], "_sample_test.md"), split = TRUE) } out = standardizationWrapper(data = data, tree = tree, fbsTree = fbsTree, standParams = params, printCodes = printCodes, nutrientData = nutrientData, debugFile = params$createIntermetiateFile ,batchnumber = batchnumber, utilizationTable = utilizationTable, cutItems=cutItems) return(out) } ## Split data based on the two factors we need to loop over uniqueLevels = data[, .N, by = c("geographicAreaM49", "timePointYears")] uniqueLevels[, N := NULL] parentNodes = getCommodityLevel(tree, parentColname = "measuredItemParentCPC", childColname = "measuredItemChildCPC") parentNodes = parentNodes[level == 0, node] aggFun = function(x) { if (length(x) > 1) stop("x should only be one value!") return(sum(x)) } standData = vector(mode = "list", length = nrow(uniqueLevels)) # Create Local Temporary File for Intermediate Savings if(CheckDebug()){ basedir=getwd() }else{ basedir <- tempfile() } if(params$createIntermetiateFile){ if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv")) } } message("Beginning actual standardization process...") ## Run all the standardization and balancig for combination of country/year ptm <- proc.time() for (i in seq_len(nrow(uniqueLevels))) { filter = uniqueLevels[i, ] dataSubset = data[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset = tree[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset[, c("geographicAreaM49", "timePointYears") := NULL] subNutrientData = nutrientData[filter, , on = c("geographicAreaM49", "timePointYears")] subNutrientData = dcast(measuredItemSuaFbs ~ measuredElement, data = subNutrientData, value.var = "Value", fun.agg = aggFun) setnames(subNutrientData, nutrientCodes, c("Calories", "Proteins", "Fats")) utilizationTableSubset = utilizationTable[get(params$geoVar)==as.character(uniqueLevels[i,1,with=FALSE])] standData[[i]] = standardizationVectorized(data = dataSubset, tree = treeSubset, nutrientData = subNutrientData, batchnumber = batchnumber, utilizationTable = utilizationTableSubset, fbsTree=fbsTree ) standData[[i]] <- rbindlist(standData[[i]]) names(standData[[i]])[grep("^fbsID", names(standData[[i]]))] <- params$itemVar standData[[i]][,(params$itemVar):= paste0("S", get(params$itemVar))] } message((proc.time() - ptm)[3]) message("Combining standardized data...") standData = rbindlist(standData) ######## CREATE EMAIL if(!CheckDebug()){ # Create the body of the message # FILETYPE = ".csv" CONFIG <- faosws::GetDatasetConfig(sessionKey@domain, sessionKey@dataset) sessionid <- ifelse(length(sessionKey@sessionId), sessionKey@sessionId, "core") basename <- sprintf("%s_%s", "dataByTree", sessionid) destfile <- paste0(basedir,"/standardization") # destfile <- "/standardization" files2zip <- dir(destfile, full.names = TRUE) # define on exit strategy on.exit(file.remove(destfile)) zipfile <- paste0(destfile, ".zip") withCallingHandlers(zip(zipfile, files2zip), warning = function(w){ if(grepl("system call failed", w$message)){ stop("The system ran out of memory trying to zip up your data. Consider splitting your request into chunks") } }) on.exit(file.remove(zipfile), add = TRUE) body = paste("Attached you will find input output files for the country/years combinations selected" ,sep='\n') sendmailR::sendmail(from = "<EMAIL>", to = swsContext.userEmail, subject = sprintf("Input/oupput files attached"), msg = list(strsplit(body,"\n")[[1]], sendmailR::mime_part(zipfile, name = paste0(basename,".zip") ) ) ) if(!CheckDebug()){ unlink(basedir) }else{ unlink(paste0(basedir,"/debugFile/Batch_",batchnumber)) } paste0("Email sent to ", swsContext.userEmail) } <file_sep>/modules/SUA_bal_compilation_round2021/Derived_Faostat_check.R library(faosws) library(faoswsUtil) library(dplyr) library(data.table) library(tidyr) library(openxlsx) library(RcppRoll) library(stringr) library(faoswsProduction) start_time <- Sys.time() R_SWS_SHARE_PATH <- Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { R_SWS_SHARE_PATH <- "//hqlprsws1.hq.un.fao.org/sws_r_share" mydir <- "modules/SUA_bal_compilation_round2021" SETTINGS <- faoswsModules::ReadSettings(file.path(mydir, "sws.yml")) SetClientFiles(SETTINGS[["certdir"]]) GetTestEnvironment(baseUrl = SETTINGS[["server"]], token = SETTINGS[["token"]]) } COUNTRY <- as.character(swsContext.datasets[[1]]@dimensions$geographicAreaM49@keys) COUNTRY_NAME <- nameData( "aproduction", "aproduction", data.table(geographicAreaM49 = COUNTRY))$geographicAreaM49_description USER <- regmatches( swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE) ) dbg_print <- function(x) { message(paste0("Derived check in (", COUNTRY, "): ", x)) } #years to identify the outlier in the 2013-2014 gap start_year <- as.character(as.numeric(swsContext.computationParams$start_year)-1) end_year <- as.character(swsContext.computationParams$end_year) #need to extract data to have at least 3 years before to compute the mean moving avg YEARS <- as.character((as.numeric(start_year)-3):as.numeric(end_year)) #years to work with. Serie to check anomalies FOCUS_INTERVAL <- start_year:end_year #startYear <- 2013 #endYear <- 2019 `%!in%` <- Negate(`%in%`) #################################################### tmp file + email ################################# TMP_DIR <- file.path(tempdir(), USER) if (!file.exists(TMP_DIR)) dir.create(TMP_DIR, recursive = TRUE) #"IMBALANCE_", COUNTRY, ".xlsx" tmp_file_derived <- file.path(TMP_DIR, paste0("Anomalies_derived_", COUNTRY,".xlsx")) expandYear = function(data, areaVar = "geographicAreaM49", elementVar = "measuredElementSuaFbs", itemVar = "measuredItemFbsSua", yearVar = "timePointYears", valueVar = "Value", obsflagVar="flagObservationStatus", methFlagVar="flagMethod", newYears=NULL){ key = c(elementVar, areaVar, itemVar) keyDataFrame = data[, key, with = FALSE] keyDataFrame=keyDataFrame[with(keyDataFrame, order(get(key)))] keyDataFrame=keyDataFrame[!duplicated(keyDataFrame)] yearDataFrame = unique(data[,get(yearVar)]) if(!is.null(newYears)){ yearDataFrame=unique(c(yearDataFrame, newYears, newYears-1, newYears-2)) } yearDataFrame=data.table(yearVar=yearDataFrame) colnames(yearDataFrame) = yearVar completeBasis = data.table(merge.data.frame(keyDataFrame, yearDataFrame)) expandedData = merge(completeBasis, data, by = colnames(completeBasis), all.x = TRUE) expandedData = fillRecord(expandedData,areaVar=areaVar,itemVar=itemVar, yearVar=yearVar ) ##------------------------------------------------------------------------------------------------------------------ ## control closed series: if in the data pulled from the SWS, the last protected value is flagged as (M,-). ## In this situation we do not have to expand the session with (M, u), but with (M, -) in order to ## avoid that the series is imputed for the new year ## 1. add a column containing the last year for which it is available a PROTECTED value seriesToBlock=expandedData[(get(methFlagVar)!="u"),] #seriesToBlock[,lastYearAvailable:=max(timePointYears), by=c( "geographicAreaM49","measuredElement","measuredItemCPC")] seriesToBlock[,lastYearAvailable:=max(get(yearVar)), by=key] ## 2. build the portion of data that has to be overwritten seriesToBlock[,flagComb:=paste(get(obsflagVar),get(methFlagVar), sep = ";")] seriesToBlock=seriesToBlock[get(yearVar)==lastYearAvailable & flagComb=="M;-"] ##I have to expand the portion to include all the yers up to the last year if(nrow(seriesToBlock)>0){ seriesToBlock=seriesToBlock[, {max_year = max(as.integer(.SD[,timePointYears])) data.table(timePointYears = seq.int(max_year + 1, newYears), Value = NA_real_, flagObservationStatus = "M", flagMethod = "-")[max_year < newYears]}, by = key] setDT(seriesToBlock)[, ("timePointYears") := lapply(.SD, as.character), .SDcols = "timePointYears"] ##I have to expand the portion to include all the yers up to the last year expandedData= merge(expandedData, seriesToBlock, by = c(areaVar, elementVar, itemVar, yearVar), all.x=TRUE, suffixes = c("","_MDash")) expandedData[!is.na(flagMethod_MDash),flagMethod:=flagMethod_MDash] expandedData[!is.na(flagObservationStatus_MDash),flagObservationStatus:=flagObservationStatus_MDash] expandedData=expandedData[,colnames(data),with=FALSE] } expandedData } #New version with unlink of the temporary folders integrated send_mail <- function(from = NA, to = NA, subject = NA, body = NA, remove = FALSE) { if (missing(from)) from <- '<EMAIL>' if (missing(to)) { if (exists('swsContext.userEmail')) { to <- swsContext.userEmail } } if (is.null(to)) { stop('No valid email in `to` parameter.') } if (missing(subject)) stop('Missing `subject`.') if (missing(body)) stop('Missing `body`.') if (length(body) > 1) { body <- sapply( body, function(x) { if (file.exists(x)) { # https://en.wikipedia.org/wiki/Media_type file_type <- switch( tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), txt = 'text/plain', csv = 'text/csv', png = 'image/png', jpeg = 'image/jpeg', jpg = 'image/jpeg', gif = 'image/gif', xls = 'application/vnd.ms-excel', xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', doc = 'application/msword', docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf = 'application/pdf', zip = 'application/zip', # https://stackoverflow.com/questions/24725593/mime-type-for-serialized-r-objects rds = 'application/octet-stream' ) if (is.null(file_type)) { stop(paste(tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), 'is not a supported file type.')) } else { res <- sendmailR:::.file_attachment(x, basename(x), type = file_type) if (remove == TRUE) { unlink(x) } return(res) } } else { return(x) } } ) } else if (!is.character(body)) { stop('`body` should be either a string or a list.') } sendmailR::sendmail(from, to, subject, as.list(body)) } ############################################################################################################## derived_selected <- c("24310.01","01921.02","0143","21700.02","23540","2166","2168","2162","21691.12","21691.02", "2167","2165","21691.14","21641.01","21631.02","21691.07","2161","21631.01","01491.02","2351f", "24212.02","22249.01","22249.02","22242.01","22241.01","22254","22252","22253","22251.02", "22251.01","22120","22241.02","22242.02","22230.04","22222.02","22110.02","22212","22221.02", "22222.01","22211","22221.01","22130.03","22130.02","22230.01","26110","21523","21521") key <- swsContext.datasets[[1]] key@dimensions$timePointYears@keys <- as.character(YEARS) key@dimensions$measuredItemFbsSua@keys <- derived_selected key@dimensions$measuredElementSuaFbs@keys <- "5510" key@dimensions$geographicAreaM49@keys <- COUNTRY data <- GetData(key) if(nrow(data) == 0){ wb <- createWorkbook(USER) saveWorkbook(wb, tmp_file_derived, overwrite = TRUE) body_message = paste("Plugin completed. No derived faostat data to check", sep='\n') send_mail(from = "<EMAIL>", to = swsContext.userEmail, subject = paste0("Derived outliers in ", COUNTRY_NAME), body = c(body_message, tmp_file_derived)) unlink(TMP_DIR, recursive = TRUE) print('No derived Faostat data to check') stop('No derived Faostat data to check') } processedData <- expandYear( data = data, areaVar = "geographicAreaM49", elementVar = "measuredElementSuaFbs", itemVar = "measuredItemFbsSua", valueVar = "Value", yearVar = "timePointYears", newYears=as.numeric(end_year) ) ############################################### ########## OUTLIERS ROUTINE 13-19 ############# ############################################### out_data <- copy(processedData) dbg_print("Data processed") out_data[order(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears), avg := roll_meanr(Value, 3, na.rm = TRUE), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[order(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears),prev_avg:=lag(avg), by= c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs")] out_data[, avg := NULL] out_data <- out_data[order(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua),] [order( -timePointYears ),] out_data <- out_data[timePointYears %in% as.character(start_year:end_year),] out_data[,flag_Check:=ifelse(flagObservationStatus %in% c("","T"),TRUE,FALSE)] out_data[,`:=`(lower_th = NA_real_, upper_th = NA_real_)] ###################################### # # # # # STRICT CRITERIA # # # # # ###################################### out_data[Value < 100 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*5, upper_th = prev_avg + prev_avg*5 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] dbg_print("line 268") out_data[ Value >= 100 & Value < 1000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*2, upper_th = prev_avg + prev_avg*2 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 1000 & Value < 5000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*1.5, upper_th = prev_avg + prev_avg*1.5 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 5000 & Value < 10000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.7, upper_th = prev_avg + prev_avg*0.7 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 10000 & Value < 50000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.6, upper_th = prev_avg + prev_avg*0.6 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 50000 & Value < 100000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.5, upper_th = prev_avg + prev_avg*0.5 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 100000 & Value < 500000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.4, upper_th = prev_avg + prev_avg*0.4 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 500000 & Value < 1000000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.3, upper_th = prev_avg + prev_avg*0.3 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 1000000 & Value < 3000000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.15, upper_th = prev_avg + prev_avg*0.15 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 3000000 & Value < 50000000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.1, upper_th = prev_avg + prev_avg*0.1 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value>=50000000 & flag_Check == FALSE, `:=`( lower_th = prev_avg - prev_avg*0.1, upper_th = prev_avg + prev_avg*0.1 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] dbg_print("End of strict criteria") ###################################### # # # # # SOFT CRITERIA # # # # # ###################################### out_data[Value < 100 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*9, upper_th = prev_avg + prev_avg*9 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] dbg_print("line 346") out_data[ Value >= 100 & Value < 1000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*5, upper_th = prev_avg + prev_avg*5 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 1000 & Value < 10000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*1, upper_th = prev_avg + prev_avg*1 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 10000 & Value < 50000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.7, upper_th = prev_avg + prev_avg*0.7 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 50000 & Value < 100000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.6, upper_th = prev_avg + prev_avg*0.6 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 100000 & Value < 500000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.5, upper_th = prev_avg + prev_avg*0.5 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 500000 & Value < 1000000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.4, upper_th = prev_avg + prev_avg*0.4 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 1000000 & Value < 3000000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.4, upper_th = prev_avg + prev_avg*0.4 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 3000000 & Value < 20000000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.3, upper_th = prev_avg + prev_avg*0.3 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value >= 20000000 & Value < 50000000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.15, upper_th = prev_avg + prev_avg*0.15 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] out_data[ Value>=50000000 & flag_Check == TRUE, `:=`( lower_th = prev_avg - prev_avg*0.1, upper_th = prev_avg + prev_avg*0.1 ), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] dbg_print("End of soft criteria") ####################################################FINAL CHECK##################################################### #1)outlier since Value out of range wrt previous average out_data[,outCheck:=ifelse(Value <lower_th | Value > upper_th ,TRUE,FALSE)] out_data[(prev_avg/Value) > 9 ,outCheck:=TRUE] out_data[Value < 1000 & prev_avg < 1000, outCheck:=FALSE] #2) outliers since previous average ha positiva value and the current is either 0 or na out_data[,zeroCheck:=ifelse(prev_avg > 0 & Value == 0 ,TRUE,FALSE)] out_data[,sparseCheck:=ifelse(prev_avg == 0 & is.na(Value) ,TRUE,FALSE)] out_data[,naCheck:=ifelse(prev_avg > 0 & is.na(Value) ,TRUE,FALSE)] ############################################### ########### Growth ROUTINE 11-12 ############## ############################################### # gr_data <- processedData[timePointYears %in% c("2010","2011","2012"),] # # gr_data <- gr_data[order(geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs, timePointYears)] # # gr_data[, # `:=`( # growth_rate = Value / shift(Value) - 1 # ), # by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") # ] # # gr_data[,flag_Check:=ifelse(flagObservationStatus %in% "T",TRUE,FALSE)] # # gr_data[,`:=`(grCheck = FALSE)] # ###################################### # # # # # # # # G RATE CRITERIA # # # # # # # # ###################################### # # #### STRICT #### # # gr_data[Value < 100 & growth_rate > 5 & flag_Check == FALSE | Value < 100 & growth_rate < -5 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 100 & Value < 1000 & growth_rate > 2 & flag_Check == FALSE | Value >= 100 & Value < 1000 & growth_rate < -2 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 1000 & Value < 5000 & growth_rate > 1.5 & flag_Check == FALSE | Value >= 1000 & Value < 5000 & growth_rate < -1.5 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 5000 & Value < 10000 & growth_rate > 0.7 & flag_Check == FALSE | Value >= 5000 & Value < 10000 & growth_rate < -0.7 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 10000 & Value < 50000 & growth_rate > 0.6 & flag_Check == FALSE | Value >= 10000 & Value < 50000 & growth_rate < -0.6 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 50000 & Value < 100000 & growth_rate > 0.5 & flag_Check == FALSE | Value >= 50000 & Value < 100000 & growth_rate < -0.5 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 100000 & Value < 500000 & growth_rate > 0.4 & flag_Check == FALSE | Value >= 100000 & Value < 500000 & growth_rate < -0.4 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 500000 & Value < 1000000 & growth_rate > 0.3 & flag_Check == FALSE | Value >= 500000 & Value < 1000000 & growth_rate < -0.3 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 1000000 & Value < 3000000 & growth_rate > 0.15 & flag_Check == FALSE| Value >= 1000000 & Value < 3000000 & growth_rate < -0.15 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value >= 3000000 & Value < 50000000 & growth_rate > 0.1 & flag_Check == FALSE | Value >= 3000000 & Value < 50000000 & growth_rate < -0.1 & flag_Check == FALSE, grCheck := TRUE] # # gr_data[ Value>=50000000 & growth_rate > 0.1 & flag_Check == FALSE | Value>=50000000 & growth_rate < -0.1 & flag_Check == FALSE, grCheck := TRUE] # # #### SOFT #### # # gr_data[Value < 100 & growth_rate > 9 & flag_Check == TRUE | Value < 100 & growth_rate < -9 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 100 & Value < 1000 & growth_rate > 5 & flag_Check == TRUE | Value >= 100 & Value < 1000 & growth_rate < -5 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 1000 & Value < 10000 & growth_rate > 1 & flag_Check == TRUE | Value >= 1000 & Value < 10000 & growth_rate < -1 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 10000 & Value < 50000 & growth_rate > 0.7 & flag_Check == TRUE | Value >= 10000 & Value < 50000 & growth_rate < -0.7 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 50000 & Value < 100000 & growth_rate > 0.6 & flag_Check == TRUE | Value >= 50000 & Value < 100000 & growth_rate < -0.6 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 100000 & Value < 500000 & growth_rate > 0.5 & flag_Check == TRUE | Value >= 100000 & Value < 500000 & growth_rate < -0.5 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 500000 & Value < 1000000 & growth_rate > 0.4 & flag_Check == TRUE | Value >= 500000 & Value < 1000000 & growth_rate < -0.4 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 1000000 & Value < 3000000 & growth_rate > 0.4 & flag_Check == TRUE | Value >= 1000000 & Value < 3000000 & growth_rate < -0.4 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 3000000 & Value < 20000000 & growth_rate > 0.3 & flag_Check == TRUE | Value >= 3000000 & Value < 20000000 & growth_rate < -0.3 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value >= 20000000 & Value < 50000000 & growth_rate > 0.15 & flag_Check == TRUE | Value >= 20000000 & Value < 50000000 & growth_rate < -0.15 & flag_Check == TRUE, grCheck := TRUE] # # gr_data[ Value>=50000000 & growth_rate > 0.1 & flag_Check == TRUE | Value>=50000000 & growth_rate < -0.1 & flag_Check == TRUE, grCheck := TRUE] # # # dbg_print("End of gr criteria") ############ filter outliers data ############ outliers1 <- out_data[outCheck==TRUE | zeroCheck ==TRUE | sparseCheck == TRUE |naCheck == TRUE,] #outliers2 <- gr_data[grCheck == TRUE,] # outlier_final <- rbind(outliers1[, c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua","timePointYears","Value","flagObservationStatus"), with= FALSE], # outliers2[, c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua","timePointYears","Value","flagObservationStatus"), with = FALSE]) outlier_final <- outliers1[,c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua","timePointYears","Value","flagObservationStatus"), with= FALSE] #trasforma i valori con la virgola qui ######################## EXPAND FORM ##################### data_dcast <- processedData[measuredItemFbsSua %in% unique(outlier_final$measuredItemFbsSua) & timePointYears %in% YEARS,] data_dcast$Value = format(round(data_dcast$Value, 0),nsmall=0 , big.mark=",",scientific=FALSE) shrink_flag <- unite(data_dcast, flag, c(flagObservationStatus,flagMethod), remove=TRUE, sep = "") shrink_flag <- unite(shrink_flag, Value, c(Value,flag), remove=TRUE, sep = " ") if (nrow(shrink_flag) > 0) { data_dcast <- dcast(shrink_flag, geographicAreaM49 + measuredElementSuaFbs + measuredItemFbsSua ~ timePointYears, value.var = c("Value")) data_dcast <- nameData("suafbs", "sua_balanced", data_dcast) } ###################################### # # # # # 2019 missing # # # # # ###################################### check_last_year <- copy(processedData) check_last_year[order(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears), avg := roll_meanr(Value, 3, na.rm = TRUE), by = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua")] check_last_year[order(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears),prev_avg:=lag(avg), by= c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs")] check_last_year[, avg := NULL] check_last_year <- check_last_year[order(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua),] [order( -timePointYears ),] check_last_year[,`:=`(missing = FALSE)] #se il 19 manca anche solo imputation da segnalare. avendo fatto expand year ed essendoci processed data dovrebbe bastare questo check #aggiungi & prev_avg => 0 (per vedere se gli anni precedenti esistono. ma chiedi a irina come gestiamo casi come 22241.02 in Bulgaria) missing_last_year <- check_last_year[is.na(Value) & timePointYears %in% as.character(tail(YEARS,1)) & prev_avg >= 0, missing := TRUE] #se il 19 c e e non è ufficiale mentre negli anni prima c e almeno un ufficiale missing_last_year[, `:=`( mean = mean(Value[timePointYears %in% as.character((tail(FOCUS_INTERVAL,1)-2): (tail(FOCUS_INTERVAL,1)))], na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemFbsSua", "measuredElementSuaFbs") ] missing_last_year = missing_last_year[!is.nan(mean),] ########################################### #### RIMUOVI -2 metti -1 IN LAST CHECK 2019 OFFICIAL ########################################### missing_last_year[, exists:= ifelse(timePointYears %in% as.character((tail(FOCUS_INTERVAL,1)-2): (tail(FOCUS_INTERVAL,1)-1)) & flagObservationStatus %in% c("","T"),TRUE,FALSE), by = c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs")] missing_last_year[, exists:= ifelse(sum(exists) >=1 ,TRUE,FALSE), by = c("geographicAreaM49","measuredItemFbsSua","measuredItemFbsSua")] missing_last_year[,`:=`(miss_official = FALSE)] missing_last_year[timePointYears %in% as.character(tail(FOCUS_INTERVAL,1)) & flagObservationStatus %!in% c("","T") & exists == TRUE, miss_official := TRUE] missing_last_year <- missing_last_year[miss_official == TRUE | missing == TRUE,] last_check <- processedData[measuredItemFbsSua %in% unique(missing_last_year$measuredItemFbsSua),] last_check$Value = format(round(last_check$Value, 0),nsmall=0 , big.mark=",",scientific=FALSE) #miss_last_year = check_last_year[exists==TRUE & !is.na(Value) & flagObservationStatus %in% c("","T"),] #miss_last_year = processedData[measuredItemFbsSua %in% unique(miss_last_year$measuredItemFbsSua),] shrink_flag_last <- unite(last_check, flag, c(flagObservationStatus,flagMethod), remove=TRUE, sep = "") shrink_flag_last <- unite(shrink_flag_last, Value, c(Value,flag), remove=TRUE, sep = " ") if (nrow(shrink_flag_last) > 0) { data_last_dcast <- dcast(shrink_flag_last, geographicAreaM49 + measuredElementSuaFbs + measuredItemFbsSua ~ timePointYears, value.var = c("Value")) data_last_dcast <- nameData("suafbs", "sua_balanced", data_last_dcast) } dbg_print("end of derived production check.. preparing excel file") ###################################### # # # # # WORKBOOOK file # # # # # ###################################### wb <- createWorkbook(USER) if(nrow(shrink_flag) != 0){ addWorksheet(wb, "Derived_outliers") writeDataTable(wb, "Derived_outliers",data_dcast) } if(nrow(shrink_flag_last) != 0){ addWorksheet(wb, "Last_year_check") writeDataTable(wb, "Last_year_check",data_last_dcast) } # # # library(devtools) # Sys.setenv(PATH = paste("C:/Rtools/bin", Sys.getenv("PATH"), sep=";")) # Sys.setenv(BINPREF = "C:/Rtools/mingw_$(WIN)/bin/") # # saveWorkbook(wb, file = "CHECK.xlsx", overwrite = TRUE) saveWorkbook(wb, tmp_file_derived, overwrite = TRUE) body_message = paste("Plugin completed. Derived Items to check. ######### Excel sheets description ######### Derived_outliers: Anomalies in series; Last_year_check: Missing values or missing official figures identified in the last year of the analysis. ", sep='\n') send_mail(from = "<EMAIL>", to = swsContext.userEmail, subject = paste0("Derived outliers in ", COUNTRY_NAME), body = c(body_message, tmp_file_derived)) unlink(TMP_DIR, recursive = TRUE) print('Plug-in Completed, check email') <file_sep>/modules/FoodResidualComputation/main.R #This script overwrites the food value for "food Residual" (given the item is not a priamry item) only if the figures are unprotected. Otherwise, figures are #not touched. #First, it takes into consideration food values of food residual items in sua unbalanced table. #Then,it selects only the unprotected food figures with the help of the flag validation table. #Next, it overwrites those food estimates with the new food estimates computed with the updated production, trade and utilization elements data as #foodHat = (prodcution + import - export- (feed+seed+tourist+loss+industrial+stock)). Then, foodHat becomes the new estimated food residual. Finally, these updated data are overwritten in sua unbalanced table. ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/FoodResidualComputation//sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } startYear1 = 2004 startYear=2014 # endYear = 2016 endYear= as.numeric(swsContext.computationParams$endYear) geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear yearVals1 = startYear1:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] # top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, # 324,332,356,360,368,384,404,116,408,450,454,484,508, # 524,562,566,586,604,608,716,646,686,762,834,764,800, # 854,704,231,887,894,760,862,860) top48FBSCountries= c() top48FBSCountries<-as.character(top48FBSCountries) selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # ##Select the countries based on the user input parameter # selectedGEOCode = # switch(geoM49, # "session" = sessionCountries, # "all" = selectedCountries) selectedGEOCode = sessionCountries ######################################### ##### Pull from SUA unbalanced data ##### ######################################### message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleDim <- Dimension(name = "measuredElementSuaFbs", keys = c("5510", "5610", "5071", "5023", "5910", "5016", "5165", "5520","5525","5164","5166","5141")) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) timeDim1 <- Dimension(name = "timePointYears", keys = as.character(yearVals1)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim1 )) #Pull SUA Data suaData = GetData(key,omitna = F,normalized=F) suaData=normalise(suaData, areaVar = "geographicAreaM49", itemVar = "measuredItemFbsSua", elementVar = "measuredElementSuaFbs", yearVar = "timePointYears", flagObsVar = "flagObservationStatus", flagMethodVar = "flagMethod", valueVar = "Value", removeNonExistingRecords = F) suaData=setDT(suaData) suaData[measuredElementSuaFbs==5164,Value:=0] suaData[measuredElementSuaFbs==5164, flagObservationStatus:="E"] suaData[measuredElementSuaFbs==5164, flagMethod:="e"] touristData=suaData[measuredElementSuaFbs==5164] ### flip data to restore NAs ## pull trade data and calculate net exports shareData <- subset(suaData, (measuredElementSuaFbs %in% c("5610","5910","5141","5510")) & timePointYears<2014 ) shareData[, c("flagObservationStatus","flagMethod"):= NULL] shareData <- dcast.data.table(shareData, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value") setnames(shareData, "5610", "imports") setnames(shareData, "5910", "exports") setnames(shareData, "5141", "food") setnames(shareData, "5510", "production") shareData[is.na(imports), imports := 0] shareData[is.na(exports), exports := 0] shareData[is.na(food), food := 0] shareData[, netTrade := (exports - imports)] shareData[,share:=food/imports] shareData[is.infinite(share), share := NA] shareData=setDT(shareData) shareData[, medshare := median(share,na.rm = T), by=c("measuredItemFbsSua")] shareData[, medfood := median(food,na.rm = T), by=c("measuredItemFbsSua")] shareData[, noProd := median(production,na.rm = T), by=c("measuredItemFbsSua")] shares=shareData[,list(share=unique(medshare), noProd=unique(noProd)), by=measuredItemFbsSua] #Pull only food data in order to create a dataframe with the CPC COdes for food foodData=subset(suaData, measuredElementSuaFbs == "5141" & timePointYears %in% yearVals) setnames(foodData,"Value", "food") #Since the food classification table contains data for all countries, it is not necessary to pull data for all countries unless or otheriwse selected geo codes are "all". #Prepare geo codes to pull only food classification for the countries the user defines. #This saves a lot of time. geoCodes_classification <- copy(selectedGEOCode)%>% as.character %>% shQuote(type = "sh") %>% paste0(collapse = ", ") # Pull food classifications only for the countries the user defines. food_classification_country_specific <- ReadDatatable("food_classification_country_specific", where = paste0("geographic_area_m49 IN (", geoCodes_classification, ")")) # food_classification_country_specific <- ReadDatatable("food_classification_country_specific") setnames(food_classification_country_specific, old = c("geographic_area_m49", "measured_item_cpc", "food_classification"), new = c("geographicAreaM49", "measuredItemFbsSua", "foodClassification")) # Define all primary and proxy primaries. This includes no parent items, cutitems and zero proessing levels and also primaries among orphans. #Further, orphans are defined as the items who are neither in tree (as a child or parent) nor cut items (proxy primary). But an orphan can be a primary. # # # primaryProxyPrimary <- c("24220", "21529.03", "21523", "2351f", "23670.01", "01447", "2161", "2162", "21631.01", "21641.01", "21641.02", "2168", "21691.14", # "2165", "2166", "21691.07", "2167", "21673", "21691.01", "21691.02", "21631.02", "21691.03", "21691.04", "21691.05", "21691.06", "21691.08", # "21691.09", "21691.10", "21691.11", "21691.12", "21691.13", "21691.90", "23620", "34550", "21693.03", "24212.02", "24310.01", "24230.01", # "24230.02", "24230.03", "24310.02", "24310.03", "24310.04", "22241.01","22241.02", "22242.01", "22242.02", "22249.01", "22249.02", "22120", # "2413", "23991.01", "24110", "23511.02", "21700.01", "21700.02","34120", "21932.02", "0111", "0112", "0113", "0114", "0115", # "0116", "0117", "0118", "01191", "01192", "01193", "01194", "01195","01199.02", "01199.90", "01211", "01212", "01213", "01215", "01216", # "01221", "01231", "01232", "01233", "01234", "01235", "01241.01","01241.90", "01242", "01243", "01251", "01252", "01253.01", "01253.02", # "01270", "01290.01", "01290.90", "01311", "01312", "01313", "01314","01315", "01316", "01318", "01319", "01321", "01322", "01323", # "01324", "01329", "01330", "01341", "01342.01", "01342.02", "01343","01344.01", "01344.02", "01345", "01346", "01349.20", "01351.02", # "01351.01", "01353.01", "01354", "01355.02", "01355.90", "01359.90","01371", "01372", "01374", "01375", "01376", "01377", "01379.90", # "0141", "0142", "01441", "01442", "01443", "01444", "01445","01446", "01449.01", "01449.02", "01449.90", "01450", "01460", # "01491.01", "01499.01", "01499.02", "01499.04", "01499.05", "01510","01520.01", "01530", "01550", "01599.10", "01610", "01640", "01691", # "01701", "01702", "01703", "01704", "01705", "01707", "01709.01", "01709.90", "01801", "01802", "01809", "01921.01", "01930.02", # "01950.01", "02211", "02212", "02291", "02292", "0231", "02910","02951.01", "02951.03", "02952.01", "02953", "02954", "21111.01", # "21113.01", "21121", "21123", "21124", "21151", "21170.02", "21170.92", "21511.01", "21512", "21513", "21514", "21515", "01591", "01540", # "01706", "01708", "01709.02", "01373", "01379.02", "01379.01","01499.03", "01448", "01214", "01219.01", "01254", "01239.01", # "01356", "01349.10", "01355.01", "01229", "01359.01", "01359.02", "01352", "01317", "01620", "01630", "01651", "01652", "01656", # "01658", "01655", "01653", "01654", "01657", "01699", "21112","21115", "21116", "21122", "21170.01", "21118.01", "21118.02", # "21118.03", "21117.01", "21114", "21119.01", "21117.02", "02920","21152", "21155", "21156", "21153", "21160.03", "21159.01", "21159.02", # "21519.02", "21519.03", "0232", "02293") commDef=ReadDatatable("fbs_commodity_definitions") primaryProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | primary_commodity=="X"]] primary=commDef$cpc[commDef[,primary_commodity=="X"]] proxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | derived=="X"]] #Merge food data and classification table foodData <- merge(foodData, food_classification_country_specific, by = c("geographicAreaM49", "measuredItemFbsSua"),all.x = T) setnames(foodData, "foodClassification", "type") # foodData <- foodData[type %in% c("Food Residual")] keys = c("flagObservationStatus", "flagMethod") foodDataMerge <- merge(foodData, flagValidTable, by = keys, all.x = T) # Discussed in a meeting: change from M- to Mu foodDataMerge[flagObservationStatus == "M" & flagMethod == "-", flagMethod := "u"] ## Checking countries with zero food figures checkTotFood = foodDataMerge[, list(totFood = sum(food)), by = list(geographicAreaM49, timePointYears)] checkTotFood = nameData("suafbs", "sua_unbalanced", checkTotFood) # checkTotFood[totFood == 0, .N, c("geographicAreaM49", "geographicAreaM49_description")] # checkTotFood[timePointYears %in% referenceYearRange & totFood == 0, .N, geographicAreaM49] excludeCountry = unique(checkTotFood[totFood == 0]$geographicAreaM49) foodDataMerge = foodDataMerge[!(geographicAreaM49 %in% excludeCountry)] ## Create time series data set for the calculations timeSeriesData <- as.data.table(expand.grid(timePointYears = as.character(startYear:endYear), geographicAreaM49 = unique(foodDataMerge$geographicAreaM49), measuredItemFbsSua = unique(foodDataMerge$measuredItemFbsSua))) timeSeriesData <- merge(timeSeriesData,food_classification_country_specific, by = c("geographicAreaM49","measuredItemFbsSua"), all.x = TRUE) setnames(timeSeriesData, "foodClassification", "type") # timeSeriesData <- subset(timeSeriesData, type == "Food Residual") timeSeriesData <- merge(timeSeriesData, foodDataMerge, all.x = T, by = c("geographicAreaM49", "timePointYears", "measuredItemFbsSua", "type")) timeSeriesData[, measuredElementSuaFbs := "5141"] #### puling global food classification table food_classicfication_global = ReadDatatable("food_classification") food_classicfication_global=food_classicfication_global[, .(measured_item_cpc, type)] setnames(food_classicfication_global,c("measured_item_cpc","type"),c("measuredItemFbsSua","type_global")) timeSeriesData <- merge(timeSeriesData,food_classicfication_global,by = c("measuredItemFbsSua"),all.x = TRUE ) timeSeriesData[, type := ifelse(is.na(food), type_global,type)] timeSeriesData[,type_global := NULL] timeSeriesData = subset(timeSeriesData , type == "Food Residual") #pull trade data tradeData <- subset(suaData, measuredElementSuaFbs %in% c("5610","5910") ) tradeData[, c("flagObservationStatus","flagMethod"):= NULL] tradeData <- dcast.data.table(tradeData, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value") setnames(tradeData, "5610", "imports") setnames(tradeData, "5910", "exports") tradeData[is.na(imports), imports := 0] tradeData[is.na(exports), exports := 0] tradeData[, netTrade := (imports - exports)] ## Merge timeseries data and tradedata keys <- c("geographicAreaM49", "timePointYears", "measuredItemFbsSua") timeSeriesData <- merge(timeSeriesData, tradeData, by = keys, all.x = T) timeSeriesData[is.na(netTrade), netTrade := 0] timeSeriesData[is.na(imports), imports := 0] timeSeriesData[is.na(exports), exports := 0] #pull production data productionData <- subset(suaData,measuredElementSuaFbs == "5510" ) productionData[, c("measuredElementSuaFbs", "flagObservationStatus", "flagMethod") := NULL] #merge production and timeseries data keys = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") timeSeriesData = merge(timeSeriesData, productionData, by = keys, all.x = T) setnames(timeSeriesData, "Value", "production") timeSeriesData[is.na(production), production := 0] timeSeriesData[, netSupply := netTrade + production] ################## CARLO keys = c("measuredItemFbsSua") timeSeriesData <- merge(timeSeriesData,shares, by=keys, all.x = TRUE) timeSeriesData=setDT(timeSeriesData) timeSeriesData[(dplyr::near(food, 0) | is.na(food)) & noProd>0, food:=share*imports] ## CARLO timeSeriesData[food>0 & is.na(noProd) & netSupply<0, food:=0] ## CARLO # Pull other elements stock, feed,seed,loss,industrial and tourist otherElements <-subset(suaData,measuredElementSuaFbs %in% c("5071","5525","5520","5016","5165","5164") ) otherElements[, c("flagObservationStatus","flagMethod") := NULL] otherElements <- dcast.data.table(otherElements, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value") if (!is.na(colnames(otherElements)["5164"])){ setnames(otherElements, c("5016","5071","5164","5165","5520","5525"), c("loss","stock","tourist","industrial","feed","seed")) } else { setnames(otherElements, c("5016","5071","5165","5520","5525"), c("loss","stock","industrial","feed","seed")) } #merge other elements to the time series table keys = c("geographicAreaM49", "measuredItemFbsSua", "timePointYears") timeSeriesData <- merge(timeSeriesData,otherElements, by=keys, all.x = TRUE) timeSeriesData[is.na(Protected), Protected := FALSE] timeSeriesData[, primary := ifelse(measuredItemFbsSua %in% primary, "primary", "not-primary")] #compute food for non-primary items #Assign zero for NA before the calculation if (!is.na(colnames(timeSeriesData)["5164"])){ cols= c("stock","loss","industrial","feed","seed","tourist") } else { cols= c("stock","loss","industrial","feed","seed") } for (j in cols) set(timeSeriesData,which(is.na(timeSeriesData[[j]])),j,0) if (!is.na(colnames(timeSeriesData)["5164"])){ timeSeriesData[primary == "not-primary", foodHat_nonprimary := netSupply - (stock+feed+seed+loss+industrial+tourist)] } else { timeSeriesData[primary == "not-primary", foodHat_nonprimary := netSupply - (stock+feed+seed+loss+industrial)] } ########################## #Compute new food residual estimate . The calcualtions are done only for the unprotected food figures. # timeSeriesData[Protected == FALSE & primary == "primary" & netSupply > 0, # foodHat:= netSupply] # # timeSeriesData[Protected == FALSE & primary == "primary" & netSupply <= 0, # foodHat := food] # changed by carlo timeSeriesData[Protected == FALSE & primary == "not-primary" & foodHat_nonprimary > 0 , foodHat := foodHat_nonprimary] timeSeriesData[Protected == FALSE & primary == "not-primary" & foodHat_nonprimary <= 0, foodHat := food] # changed by carlo # Restructure and filter data to save in SWS cat("Restructure and filter data to save in SWS...\n") dataTosave <- timeSeriesData[!is.na(foodHat)] dataTosave <- dataTosave[,c("geographicAreaM49","measuredItemFbsSua", "timePointYears","measuredElementSuaFbs", "foodHat"),with = FALSE] setnames(dataTosave, "foodHat", "Value") dataTosave[ , flagObservationStatus := "I"] dataTosave[, flagMethod := "i"] dataTosave=rbind(dataTosave,touristData) #2010 is adhoc variable. dataTosave <- subset(dataTosave, timePointYears %in% c(2010:endYear)) setcolorder(dataTosave, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears", "Value", "flagObservationStatus", "flagMethod")) # Save final data to SWS cat("Save the final data...\n") stats = SaveData(domain = "suafbs", dataset = "sua_unbalanced", data = setDT(dataTosave), waitTimeout = 1800) paste0("Food Residual are over-written with the updated values!!! ") <file_sep>/R/calculateAvailability.R ##' Aggregate Availability ##' ##' In order to determine shares for standardization, we have to calculate ##' availability of parent commodities. For example, if fruit juice is produced ##' from both apples and oranges, and the country has 400 tonnes of apples and ##' 100 tonnes of oranges, then we should standardize 80% of fruit juice values ##' to apples and 20% to oranges. This becomes more complicated when you ##' consider the multiple levels of the tree, and that there may be trade of ##' flour, for example, which influences the availability of wheat. ##' ##' Note that availability becomes complicated with complicated graphs. For ##' example, if A is a parent of B and C, and B and C are both parents of D, ##' what is the availability of A for standardizing D? There is no clear best ##' approach, but we decided to compute availability of A for D in this case by ##' computing the availability of A, B, and C for D (i.e. aggregating the ##' imbalances over all parents in the path). In the case of A and B are ##' parents of C and C is a parent of D, we have a different problem. Imbalances ##' in C shouldn't be double counted in the imbalances of A and B, so we should ##' split C's imbalance into A and B according to availability of A and B. ##' ##' @param tree The commodity tree, specified as a data.table object. It should ##' have columns childVar (the commodity code of the child), parentVar (the ##' commodity code of the parent), extractionVar (numeric value specifying the ##' extraction rate), and possibly shareVar (numeric value specifying how the ##' commodity should be split up), all of which are specified in standParams. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' ##' @return A data.table with columns parentVar, childVar, and the availability ##' from that process. Thus, if beer could be standardized into wheat, maize ##' or barley (and there is availability in all three products) our final ##' table will have three rows (beer/wheat, beer/maize, beer/barley). ##' ##' @export ##' calculateAvailability = function(tree, standParams){ ## Since we'll be editing the tree, make a copy so we don't overwrite ## things. origTree = copy(tree[, c(standParams$parentVar, standParams$childVar, standParams$extractVar, "availability"), with = FALSE]) level = findProcessingLevel(origTree, from = standParams$parentVar, to = standParams$childVar, aupusParam = standParams) setnames(level, standParams$itemVar, standParams$parentVar) origTree = merge(origTree, level) origTree[processingLevel == 0, availability := availability * get(standParams$extractVar)] ## The initial availabilities should be reported for parents ## Parent child combinations should only have one output, but we get ## the mean just in case output = origTree[processingLevel == 0, list(availability = mean(availability)), by = c(standParams$parentVar, standParams$childVar)] editedTree = copy(origTree) ## Stop if we have a very flat tree: if (max(level$processingLevel) > 1) { for (i in 1:(max(level$processingLevel) - 1)) { ## Roll down availability copyTree = copy(origTree) # Rename parent as child and child as 'newChild' setnames(copyTree, c(standParams$parentVar, standParams$childVar), c(standParams$childVar, "newChild")) # Extraction rate comes from copyTree, so deleted here editedTree[, c("extractionRate", "processingLevel") := NULL] # Merge original tree to get child availabilities editedTree = merge(editedTree, copyTree, by = standParams$childVar, suffixes = c("", ".child"), allow.cartesian = TRUE) # Sum parent availability with child availability multiplied by # extraction rate editedTree[, availability := mean( (sapply(availability, na2zero) + sapply(availability.child, na2zero)) * get(standParams$extractVar)), by = c(standParams$childVar, "newChild")] editedTree[, c(standParams$childVar) := newChild] editedTree[, c("newChild", "availability.child") := NULL] output = rbind(output, editedTree[processingLevel == i, c(standParams$parentVar, standParams$childVar, "availability"), with = FALSE]) } } ## Because we extract edges at each level, we could possibly still get ## multiple edges (i.e. A is a parent of B and C, but C is also a parent of ## B). It's a weird case, but it exists and we need to handle it. So, just ## average the availabilities in those cases. output = output[, list(availability = mean(availability)), by = c(standParams$childVar, standParams$parentVar)] return(output) }<file_sep>/R/finalStandardizationToPrimary.R ##' Final Standardization to Primary Equivalent ##' ##' After the full SUA has been balanced, all the commodities need to be rolled ##' up to their primary equivalents. This function does this, aggregating up ##' trade and food. ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param tree The commodity tree which provides the edge structure. Note that ##' this tree may be different than the processing tree, in particular if some ##' commodities will be standardized into a different aggregate. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param sugarHack Logical. See standardizeTree for details. ##' @param specificTree Logical. Is a country/year specific commodity tree ##' being provided? ##' @param additiveElements Column names of data which should be ##' aggregated/standardized via simple addition. ##' @param cut is a vector of primary Equivalent commodities ##' @return A data.table with the aggregated primary commodities. ##' ##' @export ##' finalStandardizationToPrimary = function(data, tree, standParams, sugarHack = TRUE, specificTree = TRUE, cut=c(), additiveElements = c()){ ## Note: food processing amounts should be set to zero for almost all ## commodities (as food processing shouldn't be standardized, generally). ## However, if a processed product is standardized in a different tree, then ## a balanced SUA line will NOT imply a (roughly, i.e. we still must ## optimize) balanced FBS. Thus, the food processing for grafted ## commodities should be rolled up into the parents as "Food Processing" or ## "Food Manufacturing". tree[grepl("^f\\?\\?\\?_",get(standParams$childVar)), standParams$standParentVar:="TRUE" ] foodProcElements = tree[!is.na(get(standParams$standParentVar)), unique(get(standParams$childVar))] data[get(standParams$elementVar) == standParams$foodProcCode & !get(standParams$itemVar) %in% cut, Value := 0] ## Assign production of these commodities to their food processing element ## so that we can roll that up. toMerge = data[get(standParams$itemVar) %in% cut & get(standParams$elementVar) == "production", ] toMerge[, c(standParams$elementVar) := standParams$foodProcCode] toMerge = toMerge[, c(standParams$mergeKey, standParams$elementVar, "Value"), with = FALSE] data = merge(data, toMerge, by = c(standParams$mergeKey, standParams$elementVar), all.x = TRUE, suffixes = c("", ".new")) data[!is.na(Value.new), Value := Value.new] ## Now, we must adjust the commodity tree for the pruned elements. We want ## all elements to roll up to the new parent ID except for the food ## processing. Thus, we must keep both parents in the tree and use new ## codes to identify the two cases. The nodes rolling into new parentIDs ## get new_ prefixes. data[get(standParams$itemVar) %in% cut & get(standParams$elementVar) == standParams$foodProcCode, c(standParams$itemVar) := paste0("f???_", get(standParams$itemVar))] ## tree[get(standParams$childVar) %in% foodProcElements, ## c(standParams$childVar) := paste0("f???_", get(standParams$childVar))] keyCols = standParams$mergeKey[standParams$mergeKey != standParams$itemVar] if(!specificTree){ if(nrow(data[, .N, by = c(standParams$geoVar, standParams$yearVar)]) > 1) stop("If not using a specificTree, there should only be one ", "country and year!") keyCols = keyCols[!keyCols %in% c(standParams$geoVar, standParams$yearVar)] tree[, c(standParams$yearVar) := data[, get(standParams$yearVar)][1]] tree[, c(standParams$geoVar) := data[, get(standParams$geoVar)][1]] } if(dim(tree)[1]!=0){ standTree = collapseEdges(edges = tree, keyCols = keyCols, parentName = standParams$parentVar, childName = standParams$childVar, extractionName = standParams$extractVar) }else{ standTree = tree } localParams = standParams localParams$elementPrefix = "" out = data[, standardizeTree(data = .SD, tree = standTree, standParams = localParams, elements = "Value", sugarHack = sugarHack, zeroWeight= zeroWeight), by = c(standParams$elementVar)] if(length(additiveElements) > 0){ additiveTree = copy(standTree) additiveTree[, c(standParams$extractVar) := 1] nutrients = lapply(additiveElements, function(nutrient){ temp = data[get(standParams$elementVar) == standParams$foodCode, standardizeTree(data = .SD, tree = additiveTree, standParams = localParams, elements = nutrient, sugarHack = sugarHack )] temp[, Value := get(nutrient)] temp[, c(standParams$elementVar) := nutrient] temp[, c(nutrient) := NULL] temp }) out = rbind(out, do.call("rbind", nutrients)) } ## Add on the primary value for use in some special cases of ## standardization. out = merge(out, data[, c(standParams$mergeKey, standParams$elementVar,standParams$protected,standParams$official, "Value"), with = FALSE], by = c(standParams$mergeKey, standParams$elementVar), suffixes = c("", ".old"), all.x = TRUE) ## Production should never be standardized. Instead, take the primary value ## directly. But, the elements in the food processing tree won't have a ## previously assigned production, so don't do this for them. foodProcParents = tree[grepl("^f\\?\\?\\?_", get(standParams$childVar)), unique(get(standParams$parentVar))] foodProcParents = c() out[get(standParams$elementVar) %in% c(standParams$productionCode) & !get(standParams$itemVar) %in% foodProcParents , Value := Value.old] warning("The standardization approach may not work for production in ", "the case of grafted trees IF those grafted trees have more than ", "one level. This likely won't occur often, but we'll need to ", "check and confirm.") out[, Value.old := NULL] return(out) }<file_sep>/modules/supplyChecks/supplyCheck.R ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/supplyChecks/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } startYear = 2013 endYear = 2017 geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # # ##Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) ######################################### ##### Pull from SUA unbalanced data ##### ######################################### message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredElementSuaFbs") eleKeys <-eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_balanced_data = GetData(key) suaBalancedData_DES <- subset(sua_balanced_data, measuredElementSuaFbs %in% c("5510","5610","5910","664")) suaBalancedData_DES[, c("flagObservationStatus","flagMethod") := NULL] suaBalancedData_DES <- dcast.data.table(suaBalancedData_DES, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value") setnames(suaBalancedData_DES, c("5510","5610","5910","664"),c("production","imports", "exports","calories")) suaBalancedData_DES[is.na(imports), imports := 0] suaBalancedData_DES[is.na(exports), exports := 0] suaBalancedData_DES[is.na(production), production := 0] suaBalancedData_DES[is.na(calories), calories := 0] suaBalancedData_DES[,supply := production+imports-exports] #print apparent consumption apparentConsumption <- copy (suaBalancedData_DES) apparentConsumption <- subset(apparentConsumption, timePointYears %in% c(2014:2017)) apparentConsumption <- subset(apparentConsumption, supply < 0 & supply>1000) apparentConsumption<- apparentConsumption[,c("geographicAreaM49","measuredItemFbsSua","timePointYears"),with=FALSE] apparentConsumption <-nameData("suafbs","sua_unbalanced",apparentConsumption) apparentConsumption[,timePointYears_description := NULL] #### send mail bodyApparent= paste("The Email contains a list of negative apparent consumptions at sua balanced level. It is advisable to check them all one by one and decide course of action.", sep='\n') sendMailAttachment(apparentConsumption,"apparentConsumption",bodyApparent) #apparent consumption is the list of commodities,countries and years where supply is negative. #create lag supply and calories suaBalancedData_DES = split(suaBalancedData_DES, f = suaBalancedData_DES$geographicAreaM49, drop = TRUE) suaBalancedData_DES = lapply(suaBalancedData_DES, data.table) suaBalancedData_lag = list() for (i in 1:length(suaBalancedData_DES)){ data_lag= data.table(suaBalancedData_DES[[i]]) suaBalancedData_lag[[i]] <- data_lag[order(timePointYears),supply_lag:= shift(supply), by= c("measuredItemFbsSua")] suaBalancedData_lag[[i]] <- data_lag[order(timePointYears),calories_lag:= shift(calories), by= c("measuredItemFbsSua")] } data_lag_final = do.call("rbind",suaBalancedData_lag) #Assign zero for NA data_lag_final[is.na(supply_lag), supply_lag := 0] data_lag_final[is.na(calories_lag), calories_lag := 0] #Eliminiate year 2013 data_lag_final <- subset(data_lag_final, timePointYears %in% c(2014:2017)) #compute delta supply and delta calories. Ex: delta_supply_2015 = supply_2015 - supply_2014 data_lag_final[, delta_supply := supply - supply_lag] data_lag_final[, delta_calories := calories - calories_lag ] #take cases where delta supply is negative and delta calories are positive printData <- subset(data_lag_final, delta_supply < 0 & delta_calories > 2 & calories>1 ) printcases <- printData[,c("geographicAreaM49","measuredItemFbsSua","timePointYears"),with=FALSE] printcases <- nameData("suafbs","sua_unbalanced",printcases) printcases[, timePointYears_description := NULL] bodySupplyCondition= paste("The Email contains a list of cases where consumption is increasing despite a decrease in supply.", "It is advisable to adjust the figures in order to have a more realistic consumption behavior.", sep='\n') sendMailAttachment(printcases,"supplyCondition",bodySupplyCondition) <file_sep>/modules/FullstandardizationAndBalancingBIS/main.R ## load the library library(faosws) library(faoswsUtil) library(faoswsBalancing) library(faoswsStandardization) library(faoswsFlag) message("libraries loaded") library(data.table) library(igraph) library(stringr) library(dplyr) # library(dtplyr) library(MASS) library(lattice) library(reshape2) library(sendmailR) if(packageVersion("faoswsStandardization") < package_version('0.1.0')){ stop("faoswsStandardization is out of date") } ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { library(faoswsModules) message("Not on server, so setting up environment...") # Read settings file sws.yml in working directory. See # sws.yml.example for more information PARAMS <- ReadSettings("modules/fullStandardizationAndBalancingBIS/sws.yml") message("Connecting to server: ", PARAMS[["current"]]) R_SWS_SHARE_PATH = PARAMS[["share"]] apiDirectory = "./R" ## Get SWS Parameters SetClientFiles(dir = PARAMS[["certdir"]]) GetTestEnvironment( baseUrl = PARAMS[["server"]], token = PARAMS[["token"]] ) batchnumber = 000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT } else { batchnumber = 000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT message("Running on server, no need to call GetTestEnvironment...") } #User name is what's after the slash SWS_USER = regmatches(swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE)) # instead of replace the existing # (for example save example files for different batches) # put the name in the .yml file # default is NULL if(CheckDebug()){ SUB_FOLDER = paste0(PARAMS[["subShare"]],batchnumber) } message("Getting parameters/datasets...") # start and end year for standardization come from user parameters startYear = swsContext.computationParams$startYear endYear = swsContext.computationParams$endYear geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = as.character(startYear:endYear) outlierMail = swsContext.computationParams$checks ## Get data configuration and session sessionKey_fbsBal = swsContext.datasets[[1]] sessionKey_suaUnb = swsContext.datasets[[2]] sessionKey_suabal = swsContext.datasets[[3]] sessionKey_fbsStand = swsContext.datasets[[4]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey_fbsBal) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] # Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) areaKeys = selectedGEOCode ############################################################## ############ DOWNLOAD AND VALIDATE TREE ###################### ############################################################## ptm <- proc.time() tree=getCommodityTreeNewMethod(areaKeys,yearVals) message((proc.time() - ptm)[3]) validateTree(tree) # NA ExtractionRates are recorded in the sws dataset as 0 # for the standardization, we nee them to be treated as NA # therefore here we are re-changing it tree[Value==0,Value:=NA] ############################################################## ################### MARK OILS COMMODITY ###################### ############################################################## oilFatsCPC=c("2161", "2162", "21631.01", "21641.01", "21641.02", "2168", "21691.14", "2165", "34120", "21932.02", "2166", "21691.07", "2167", "21673", "21691.01", "21691.02", "21691.03", "21691.04", "21691.05", "21691.06", "21631.02", "21691.08", "21691.09", "21691.10", "21691.11", "21691.12", "21691.13", "21691.90", "23620", "21700.01", "21700.02", "21693.02", "34550", "F1275", "21512", "21512.01", "21513", "21514", "F0994", "21515", "21511.01", "21511.02", "21521", "21511.03", "21522", "21519.02", "21519.03", "21529.03", "21529.02", "21932.01", "21523", "F1243", "F0666") tree[(measuredItemParentCPC%in%oilFatsCPC|measuredItemChildCPC%in%oilFatsCPC),oil:=TRUE] ############################################################## ################ CLEAN NOT OFFICIAL SHARES ################### ################ & SHARES EXCEPT OILS ################### ############################################################## ## (E,f) have to be kept ## any other has to ve cleaned except the oils tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] tree[measuredElementSuaFbs=="share"&(checkFlags=="(E,f)"|oil==TRUE),keep:=TRUE] tree[measuredElementSuaFbs=="share"&is.na(keep),Value:=NA] tree[,checkFlags:=NULL] tree[,oil:=NULL] tree[,keep:=NULL] ############################################################## ############ Set parameters for specific dataset ############# ############################################################## params = defaultStandardizationParameters() params$itemVar = "measuredItemSuaFbs" params$mergeKey[params$mergeKey == "measuredItemCPC"] = "measuredItemSuaFbs" params$elementVar = "measuredElementSuaFbs" params$childVar = "measuredItemChildCPC" params$parentVar = "measuredItemParentCPC" params$productionCode = "production" params$importCode = "imports" params$exportCode = "exports" params$stockCode = "stockChange" params$foodCode = "food" params$feedCode = "feed" params$seedCode = "seed" params$wasteCode = "loss" params$industrialCode = "industrial" params$touristCode = "tourist" params$foodProcCode = "foodManufacturing" params$residualCode = "residual" params$createIntermetiateFile= "TRUE" params$protected = "Protected" params$official = "Official" ############################################################## ######## CLEAN ALL SESSION TO BE USED IN THE PROCESS ######### ############################################################## if(!CheckDebug()){ ## CLEAN sua_balanced message("wipe sua_balanced session") CONFIG <- GetDatasetConfig(sessionKey_suabal@domain, sessionKey_suabal@dataset) datatoClean=GetData(sessionKey_suabal) datatoClean=datatoClean[timePointYears%in%yearVals] datatoClean[, Value := NA_real_] datatoClean[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) ## CLEAN fbs_standardized message("wipe fbs_standardized session") CONFIG <- GetDatasetConfig(sessionKey_fbsStand@domain, sessionKey_fbsStand@dataset) datatoClean=GetData(sessionKey_fbsStand) datatoClean=datatoClean[timePointYears%in%yearVals] datatoClean[, Value := NA_real_] datatoClean[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) ## CLEAN fbs_balanced message("wipe fbs_balanced session") CONFIG <- GetDatasetConfig(sessionKey_fbsBal@domain, sessionKey_fbsBal@dataset) datatoClean=GetData(sessionKey_fbsBal) datatoClean=datatoClean[timePointYears%in%yearVals] datatoClean[, Value := NA_real_] datatoClean[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = datatoClean, waitTimeout = Inf) } ############################################################## #################### SET KEYS FOR DATA ####################### ############################################################## elemKeys=c("5510", "5610", "5071", "5023", "5910", "5016", "5165", "5520","5525","5164","5166","5141") # 5510 Production[t] # 5610 Import Quantity [t] # 5071 Stock Variation [t] # 5023 Export Quantity [t] # 5910 Loss [t] # 5016 Industrial uses [t] # 5165 Feed [t] # 5520 Seed [t] # 5525 Tourist Consumption [t] # 5164 Residual other uses [t] # 5166 Food [t] # 5141 Food Supply (/capita/day) [Kcal] desKeys = c("664","674","684") # 664 Food Supply (Kcal/caput/day) [kcal] # 674 Protein Supply quantity (g/caput/day) [g] # 684 Fat supply quantity (g/caput/day) [g] itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = yearVals) )) ############################################################## ####################### DOWNLOAD DATA ####################### ############################################################## message("Reading SUA data...") data = elementCodesToNames(data = GetData(key), itemCol = "measuredItemFbsSua", elementCol = "measuredElementSuaFbs") message("convert element codes into element names") data[measuredElementSuaFbs=="foodmanufacturing",measuredElementSuaFbs:="foodManufacturing"] setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") data[measuredElementSuaFbs=="stock_change",measuredElementSuaFbs:="stockChange"] data[measuredElementSuaFbs=="stock",measuredElementSuaFbs:="stockChange"] message("delete null elements") data=data[!is.na(measuredElementSuaFbs)] ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## data=convertSugarCodes(data) ############################################################## ############### CREATE THE COLUMN "OFFICIAL" ################# ############################################################## data=left_join(data,flagValidTable,by=c("flagObservationStatus","flagMethod"))%>% data.table data[flagObservationStatus%in%c("","T"),Official:=TRUE] data[is.na(Official),Official:=FALSE] ####################################### # The following copy is needed for saving back some of the intermediate # files. These intermediate steps will come without flag and the flag # will be merged with this original data object dataFlags = copy(data) ############################################################## # For DERIVED select only the protected and the estimation # (coming from the submodule of derived and Livestock) # I have to select Protected and Estimation (I,e) and (I,i) # For all the others delete the production value # this will leave the Sua Filling creting prodcution, where needed level = findProcessingLevel(tree, from = params$parentVar, to = params$childVar, aupusParam = params) primaryEl = level[processingLevel == 0, get(params$itemVar)] data[!(get(params$protected)=="TRUE"|(flagObservationStatus=="I"&flagMethod%in%c("i","e"))) &get(params$elementVar)==params$productionCode &!(get(params$itemVar) %in% primaryEl),Value:=NA] ############################################################## ################## RECALCULATE SHARE ##################### ########## FOR COMMODITIES MANUALLY ENTERED ############## ############################################################## p=params ### Compute availability and SHARE data[, availability := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, 0, ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, 0))))))))))))), by = c(p$mergeKey)] mergeToTree = data[, list(availability = mean(availability)), by = c(p$itemVar)] setnames(mergeToTree, p$itemVar, p$parentVar) plotTree = copy(tree) tree2=copy(plotTree) tree2shares=tree[measuredElementSuaFbs=="share"] tree2shares[,share:=Value] tree2shares[,c("measuredElementSuaFbs","Value"):=NULL] tree2exRa=tree[measuredElementSuaFbs=="extractionRate"] tree2exRa[,extractionRate:=Value] tree2exRa[,c("measuredElementSuaFbs","Value"):=NULL] tree2=data.table(left_join(tree2shares,tree2exRa[,c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC", "timePointYears","extractionRate"),with=FALSE], by=c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears"))) tree2=tree2[!is.na(extractionRate)] tree2 = merge(tree2, mergeToTree, by = p$parentVar, all.x = TRUE) #### SHAREs 1 # share are the proportion of availability of each parent # on the total availability by child # Function checkShareValue() checks the validity of the shares, # change wrong values # return a severity table # and the values to be saved back in the session of the TRee tree2[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] tree2[,availability.child:=availability*get(p$extractVar)] tree2[,shareSum:=sum(share),by=c("measuredItemChildCPC", "timePointYears")] # Create eventual Errors HEre for testing the checkshares function uniqueShares2change = tree2[checkFlags=="(E,f)"&(round(shareSum,3)!=1|is.na(shareSum)), .N, by = c("measuredItemChildCPC", "timePointYears")] uniqueShares2change[, N := NULL] tree2[,newShare:=NA] tree2[,severity:=NA] tree2[,message:=NA] tree2[,newShare:=as.numeric(newShare)] tree2[,severity:=as.integer(severity)] tree2[,message:=as.character(message)] tree2change = vector(mode = "list", length = nrow(uniqueShares2change)) for (i in seq_len(nrow(uniqueShares2change))) { filter = uniqueShares2change[i, ] tree2Subset = tree2[filter, , on = c("measuredItemChildCPC", "timePointYears")] tree2change[[i]] = checkShareValue(tree2Subset) } tree2change = rbindlist(tree2change) tree2merge=copy(tree2change) # Before sending it via email, change flags if(dim(tree2merge)[1]>0){ tree2merge[checkFlags!="(E,f)",flagObservationStatus:="I"] tree2merge[checkFlags!="(E,f)",flagMethod:="i"] tree2merge[,c("checkFlags","availability.child","shareSum","availability","extractionRate"):=NULL] } sendMail4shares(tree2merge) # IF SHARES ARE VALID ( and Tree2change does not exists), The " tree" is the one to use # onwards # nothing has to be done in this case # IF THERE IS A tree2change, after it has been sent, it has to be integrated in the tree # before going on if(dim(tree2merge)[1]>0){ setnames(tree2merge,"share","Value") tree2merge[,c("severity","message"):=NULL] tree2merge[,measuredElementSuaFbs:="share"] setcolorder(tree2merge,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod")) uniquecomb = tree2merge[, .N, by = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears")] uniquecomb[,N := NULL] tree=rbind(tree[!uniquecomb, ,on=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears")],tree2merge) } ############################################################## ############## LAST MANIPULATIONS ON TREE ################# ############################################################## tree[,c("flagObservationStatus","flagMethod"):=NULL] tree=data.table(dcast(tree,geographicAreaM49 + measuredItemParentCPC + measuredItemChildCPC + timePointYears ~ measuredElementSuaFbs,value.var = "Value")) tree=tree[!is.na(extractionRate)] tree=tree[!is.na(measuredItemChildCPC)] ## Update tree by setting some edges to "F" FPCommodities <- c( "01499.06", "01921.01") # These commodities are forwards processed instead of backwards processed: # code description type # 3: 01499.06 Kapokseed in shell CRNP # 4: 01921.01 Seed cotton, unginned CRPR tree[, target := ifelse(measuredItemParentCPC %in% FPCommodities, "F", "B")] # MERGE the TREE with the item Map fpr future manipulation itemMap = GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemMap = itemMap[, c("code", "type"), with = FALSE] setnames(itemMap, "code", "measuredItemSuaFbs") data = merge(data, itemMap, by = "measuredItemSuaFbs") setnames(itemMap, "measuredItemSuaFbs", "measuredItemParentCPC") tree = merge(tree, itemMap, by = "measuredItemParentCPC") ## Remove missing elements data = data[!is.na(measuredElementSuaFbs), ] data=data[,c("measuredItemSuaFbs", "measuredElementSuaFbs", "geographicAreaM49", "timePointYears", "Value", "flagObservationStatus", "flagMethod", "Valid", "Protected", "Official", "type"),with=FALSE] ####################################################### # save the initial data locally for future reports if(CheckDebug()){ dir.create(paste0(PARAMS$debugFolder,"/Batch_",batchnumber), showWarnings = FALSE,recursive=TRUE) } if(CheckDebug()){ initialSua = data save(initialSua,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_01_InitialSua_BeforeCB.RData")) } ####################################################### data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type","flagObservationStatus","flagMethod"))] # data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type"))] ############################################################# ########## LOAD NUTRIENT DATA AND CORRECT ############# ############################################################# message("Loading nutrient data...") itemKeys = GetCodeList("agriculture", "aupus_ratio", "measuredItemCPC")[, code] # Nutrients are: # 1001 Calories # 1003 Proteins # 1005 Fats nutrientCodes = c("1001", "1003", "1005") nutrientData = getNutritiveFactors(measuredElement = nutrientCodes, timePointYears = yearVals) setnames(nutrientData, c("measuredItemCPC", "timePointYearsSP"), c("measuredItemSuaFbs", "timePointYears")) # It has been found that some Nutrient Values are wrong in the Nutrient Data Dataset ######### CREAM SWEDEN nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1001",Value:=195] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1003",Value:=3] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1005",Value:=19] ### MILK SWEDEN nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1001",Value:=387] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1003",Value:=26] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1005",Value:=30] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1001",Value:=310] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1003",Value:=23] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1005",Value:=23] ################################################################# ################################################################# ################################################################# message("Download Utilization Table from SWS...") # utilizationTable=ReadDatatable("utilization_table") utilizationTable=ReadDatatable("utilization_table_percent") utilizationTable=data.table(utilizationTable) # setnames(utilizationTable,colnames(utilizationTable),c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", # "rank", "rankInv")) setnames(utilizationTable,colnames(utilizationTable),c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", "percent","rank", "rankInv")) message("Download zero Weight from SWS...") zeroWeight=ReadDatatable("zero_weight")[,item_code] # zeroWeight=data.table(zeroWeight) message("Download cutItems from SWS...") cutItems=ReadDatatable("cut_items2")[,cpc_code] # cutItems=data.table(cutItems) message("Download fbsTree from SWS...") fbsTree=ReadDatatable("fbs_tree") fbsTree=data.table(fbsTree) setnames(fbsTree,colnames(fbsTree),c( "fbsID1", "fbsID2", "fbsID3","fbsID4", "measuredItemSuaFbs")) setcolorder(fbsTree,c("fbsID4", "measuredItemSuaFbs", "fbsID1", "fbsID2", "fbsID3")) message("Defining vectorized standardization function...") standardizationVectorized = function(data, tree, nutrientData,batchnumber, utilizationTable,cutItems,fbsTree){ # record if output is being sunk and at what level sinkNumber <- sink.number() # Prevent sink staying open if function is terminated prematurely (such as # in debugging of functions in standardization) on.exit(while (sink.number() > sinkNumber) sink()) if (nrow(data) == 0) { message("No rows in data, nothing to do") return(data) } # If printCodes is length 0, neither the .md files nor plots are created # If it has a non-zero value, those are the codes which will have file outputs printCodes = character() # printCodes = c("01701") # printCodes = getChildren(commodityTree = tree, # parentColname = params$parentVar, # childColname = params$childVar, # topNodes = printCodes) if(CheckDebug()){ dir.create(paste0(R_SWS_SHARE_PATH, "/", SWS_USER, "/", SUB_FOLDER, "/standardization/") , showWarnings = FALSE,recursive = TRUE ) sink(paste0(R_SWS_SHARE_PATH, "/", SWS_USER,"/", SUB_FOLDER, "/standardization/", data$timePointYears[1], "_", data$geographicAreaM49[1], "_sample_test.md"), split = TRUE) }else{ dir.create(paste0(R_SWS_SHARE_PATH, "/", SWS_USER, "/standardization/") , showWarnings = FALSE,recursive = TRUE ) sink(paste0(R_SWS_SHARE_PATH, "/", SWS_USER,"/standardization/", data$timePointYears[1], "_", data$geographicAreaM49[1], "_sample_test.md"), split = TRUE) } out = standardizationWrapper(data = data, tree = tree, fbsTree = fbsTree, standParams = params, printCodes = printCodes, nutrientData = nutrientData, debugFile = params$createIntermetiateFile ,batchnumber = batchnumber, utilizationTable = utilizationTable, cutItems=cutItems) return(out) } ## Split data based on the two factors we need to loop over uniqueLevels = data[, .N, by = c("geographicAreaM49", "timePointYears")] uniqueLevels[, N := NULL] parentNodes = getCommodityLevel(tree, parentColname = "measuredItemParentCPC", childColname = "measuredItemChildCPC") parentNodes = parentNodes[level == 0, node] aggFun = function(x) { if (length(x) > 1) stop("x should only be one value!") return(sum(x)) } standData = vector(mode = "list", length = nrow(uniqueLevels)) # Create Local Temporary File for Intermediate Savings if(CheckDebug()){ basedir=getwd() }else{ basedir <- tempfile() } if(params$createIntermetiateFile){ if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv")) } if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv"))){ file.remove(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv")) } } message("Beginning actual standardization process...") ## Run all the standardization and balancig for combination of country/year ptm <- proc.time() for (i in seq_len(nrow(uniqueLevels))) { filter = uniqueLevels[i, ] dataSubset = data[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset = tree[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset[, c("geographicAreaM49", "timePointYears") := NULL] subNutrientData = nutrientData[filter, , on = c("geographicAreaM49", "timePointYears")] subNutrientData = dcast(measuredItemSuaFbs ~ measuredElement, data = subNutrientData, value.var = "Value", fun.agg = aggFun) setnames(subNutrientData, nutrientCodes, c("Calories", "Proteins", "Fats")) utilizationTableSubset = utilizationTable[get(params$geoVar)==as.character(uniqueLevels[i,1,with=FALSE])] standData[[i]] = standardizationVectorized(data = dataSubset, tree = treeSubset, nutrientData = subNutrientData, batchnumber = batchnumber, utilizationTable = utilizationTableSubset, fbsTree=fbsTree ) standData[[i]] <- rbindlist(standData[[i]]) names(standData[[i]])[grep("^fbsID", names(standData[[i]]))] <- params$itemVar standData[[i]][,(params$itemVar):= paste0("S", get(params$itemVar))] } message((proc.time() - ptm)[3]) message("Combining standardized data...") standData = rbindlist(standData) ## Save the StandData LOCALLY if(CheckDebug()){ save(standData,file=paste0(PARAMS$temporaryStandData,"/standDatabatch",batchnumber,".RData")) } ################################### ## AFTER SUA FILLING 1 (No intermediate saving) if(CheckDebug()){ ptm <- proc.time() if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv"))){ AfterSuaFilling1 = read.table(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.csv"), header=FALSE,sep=";",col.names=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears","Value","flagObservationStatus","flagMethod"), colClasses = c("character","character","character","character","character","character","character")) AfterSuaFilling1 = data.table(AfterSuaFilling1) message((proc.time() - ptm)[3]) # Save these data LOCALLY if(CheckDebug()){ save(AfterSuaFilling1,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_00a_AfterSuaFilling1.RData")) } } } ################################### ################################### ## AFTER FOOD PROCESSING (No intermediate saving) if(CheckDebug()){ ptm <- proc.time() if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv"))){ AfterFoodProc = read.table(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.csv"), header=FALSE,sep=";",col.names=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears","Value","flagObservationStatus","flagMethod"), colClasses = c("character","character","character","character","character","character","character")) AfterFoodProc = data.table(AfterFoodProc) message((proc.time() - ptm)[3]) # Save these data LOCALLY if(CheckDebug()){ save(AfterFoodProc,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_00b_AfterFoodProc.RData")) } } } ################################### ## FORCED COMMODITIES IN THE SUA FILLING PROCESS (to be sent by mail) print(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv")) print(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv"))) if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv"))){ FORCED_PROD = read.table(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.csv"), header=FALSE,sep=";",col.names=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears","Value","flagObservationStatus","flagMethod"), colClasses = c("character","character","character","character","character","character","character")) FORCED_PROD = data.table(FORCED_PROD) message=(paste0( length(FORCED_PROD[,unique(measuredItemFbsSua)])," commodities have a FORCED Official Production")) setnames(FORCED_PROD,"measuredItemFbsSua","measuredItemSuaFbs") setnames(dataFlags,"Value","ValueOld") setnames(FORCED_PROD,"Value","ValueForced") ForcedProd2send=data.table(left_join(FORCED_PROD[,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", "timePointYears","ValueForced"),with=FALSE],dataFlags,by=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", "timePointYears"))) # ForcedProd2send[measuredElementSuaFbs!=params$productionCode,ValueForced:="-"] ForcedProd2send[,ValueForced:=round(as.numeric(ValueForced),0)] ForcedProd2send[,ValueOld:=round(as.numeric(ValueOld),0)] ForcedProd2send[,measuredItemSuaFbs:=paste0("'",measuredItemSuaFbs)] # Save these data LOCALLY if(CheckDebug()){ save(FORCED_PROD,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_10_ForcedProduction.RData")) }else{ # or send them by email if(dim(ForcedProd2send)[1]>0){ sendMail4forced(ForcedProd2send) } } }else{ message("no Forced Production") } ################################### ### DOWNLOAD POPOULATION FOR INTERMEDIATE SAVINGS ################################### ### FIRST INTERMEDIATE SAVE message("save first intermediate file") ptm <- proc.time() print(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv"))) if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv"))){ AfterSuaFilling = read.table(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.csv"), header=FALSE,sep=";",col.names=c("geographicAreaM49","measuredItemFbsSua", "timePointYears","Value","flagObservationStatus","flagMethod", "measuredElementSuaFbs"), colClasses = c("character","character","character","character","character","character","character")) AfterSuaFilling = data.table(AfterSuaFilling) AfterSuaFilling = AfterSuaFilling[measuredElementSuaFbs%in%c(elemKeys,"664")] # AfterSuaFilling = AfterSuaFilling[,Value:=round(as.numeric(Value),0)] ## As per Team B/C request (TOMASZ) I'm saving back only the DES (684) SaveData(domain = "suafbs", dataset = "sua_balanced", data = AfterSuaFilling, waitTimeout = 20000) message((proc.time() - ptm)[3]) # Save these data LOCALLY if(CheckDebug()){ save(AfterSuaFilling,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_02_AfterSuaFilling_BeforeST.RData")) } } ################################### ## IMBALANCE ANALYSIS SAVE 3 ### SECOND INTERMEDIATE SAVE message("save second intermediate file") ptm <- proc.time() if(file.exists(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv"))){ AfterST_BeforeFBSbal = read.table(paste0(basedir,"/debugFile/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.csv"), header=FALSE,sep=";",col.names=c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears","Value","flagObservationStatus","flagMethod"), colClasses = c("character","character","character","character","character","character","character")) AfterST_BeforeFBSbal = data.table(AfterST_BeforeFBSbal) AfterST_BeforeFBSbal=AfterST_BeforeFBSbal[measuredElementSuaFbs%in%c(elemKeys,"664")] SaveData(domain = "suafbs", dataset = "fbs_standardized", data = AfterST_BeforeFBSbal, waitTimeout = 20000) message((proc.time() - ptm)[3]) # Save these data LOCALLY if(CheckDebug()){ save(AfterST_BeforeFBSbal,file=paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"_03_AfterST_BeforeFBSbal.RData")) } } # Remove all intermediate Files Create in Temp Folder if(!CheckDebug()){ unlink(basedir) }else{ unlink(paste0(basedir,"/debugFile/Batch_",batchnumber)) } if(outlierMail=="Yes"){ ################### balancing check stanData2<-AfterST_BeforeFBSbal ########################################## CHECK IMBALANCE stanData2[, imbalance := sum(ifelse(is.na(Value), 0, as.numeric(Value)) * ifelse(measuredElementSuaFbs == "5510", 1, ifelse(measuredElementSuaFbs == "5610", 1, ifelse(measuredElementSuaFbs == "5910", -1, ifelse(measuredElementSuaFbs == "5071", -1, ifelse(measuredElementSuaFbs == "5141", -1, ifelse(measuredElementSuaFbs == "5023", -1, ifelse(measuredElementSuaFbs == "5520", -1, ifelse(measuredElementSuaFbs == "5016", -1, ifelse(measuredElementSuaFbs == "5525", -1, ifelse(measuredElementSuaFbs == "5165", -1, ifelse(measuredElementSuaFbs == "5164", -1, ifelse(measuredElementSuaFbs == "5166", -1,0))))))))))))), by =c("geographicAreaM49","measuredItemFbsSua", "timePointYears") ] # stanData2[, perc.imbalance := imbalance/sum(ifelse(is.na(Value), 0, as.numeric(Value)) * ifelse(measuredElementSuaFbs == 5510, 1, ifelse(measuredElementSuaFbs == 5610, 1, ifelse(measuredElementSuaFbs == 5910, -1, ifelse(measuredElementSuaFbs == 5071, -1, ifelse(measuredElementSuaFbs == 5141, 0, ifelse(measuredElementSuaFbs == 5023, 0, ifelse(measuredElementSuaFbs == 5520, 0, ifelse(measuredElementSuaFbs == 5016, 0, ifelse(measuredElementSuaFbs == 5525, 0, ifelse(measuredElementSuaFbs == 5165, 0, ifelse(measuredElementSuaFbs == 5164, 0, ifelse(measuredElementSuaFbs == 5166, 0,0))))))))))))), by =c("geographicAreaM49","measuredItemFbsSua", "timePointYears") ] imbalances=copy(stanData2) setkeyv(imbalances,c('geographicAreaM49','measuredItemFbsSua','timePointYears')) imbalancesToSend <- subset(unique(imbalances), select = c('geographicAreaM49','measuredItemFbsSua','timePointYears','imbalance', 'perc.imbalance')) imbalancesToSend <- subset(imbalancesToSend, abs(perc.imbalance)>0.2 & abs(imbalance)>10000) imbalancesToSend<-nameData("suafbs","fbs_standardized",imbalancesToSend) bodyImbalances= paste("The Email contains a list of imbalances exceeding 20% of supply, for total amounts higher than 10 thousand tonnes", sep='\n') sendMailAttachment(imbalancesToSend,"Imbalances",bodyImbalances) } # # ################################### # # TREE TO BE RESAVED # # ### Merge the Tree with the new Values # # tree=tree[,c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears","extractionRate","share"),with=FALSE] # # tree2melt=melt(tree,id.vars = c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears"), # variable.name = "measuredElementSuaFbs",value.name = "Value") # # tree2beReExported2=tree2beReExported[,c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears","measuredElementSuaFbs","flagObservationStatus","flagMethod"),with=FALSE] # # newTree=data.table(left_join(tree2beReExported2,tree2melt,by=c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears","measuredElementSuaFbs"))) # # newTree=merge(tree2beReExported2,tree2melt, # by=c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC", # "timePointYears","measuredElementSuaFbs"),all = TRUE) # # ### Change Flags of Recalculated Shares in the Commodity Tree # # Combination not to be touched are # # newTree[measuredElementSuaFbs=="share"&(measuredItemParentCPC%in%oilFatsCPC|measuredItemChildCPC%in%oilFatsCPC),flagFix:=T] # newTree[flagObservationStatus=="E"&flagMethod=="f",flagFix:=T] # # Flags to be assigned are those of the Shares which have been calculated during the Standardization # newTree[measuredElementSuaFbs=="share"&is.na(flagFix),flagObservationStatus:="I"] # newTree[measuredElementSuaFbs=="share"&is.na(flagFix),flagMethod:="i"] # # tree2saveBack=newTree[,c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC", # "timePointYears","measuredElementSuaFbs","flagObservationStatus", # "flagMethod","Value"),with=FALSE] # # ### Before Saving Bach NA have to be changed to zero # tree2saveBack[is.na(Value),Value:=0] # # # # tree2saveBack[measuredElementSuaFbs=="extractionRate",measuredElementSuaFbs:="5423",] # tree2saveBack[measuredElementSuaFbs=="share",measuredElementSuaFbs:="5431"] # tree2saveBack[,measuredElementSuaFbs:=as.character(measuredElementSuaFbs)] # setcolorder(tree2saveBack,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", # "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", # "flagMethod")) # # setnames(tree2saveBack,c("measuredItemParentCPC","measuredItemChildCPC"),c("measuredItemParentCPC_tree","measuredItemChildCPC_tree")) # # # message("Save Commodity tree...") # # ptm <- proc.time() # SaveData(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", data = tree2saveBack, waitTimeout = 20000) # message((proc.time() - ptm)[3]) # # # # ################################### ### FINAL SAVE fbs_sua_conversion2 <- data.table(measuredElementSuaFbs=c("Calories", "Fats", "Proteins","DESfoodSupply_kCd","proteinSupplyQt_gCd","fatSupplyQt_gCd", "exports", "feed", "food", "foodManufacturing", "imports", "loss", "production", "seed", "stockChange", "residual","industrial", "tourist"), code=c("261", "281", "271","664","674","684","5910", "5520", "5141", "5023", "5610", "5016", "5510", "5525", "5071", "5166","5165", "5164")) standData = merge(standData, fbs_sua_conversion2, by = "measuredElementSuaFbs") standData[,`:=`(measuredElementSuaFbs = NULL)] setnames(standData, "code", "measuredElementSuaFbs") ## Assign flags: I for imputed (as we're estimating/standardizing) and s for ## "sum" (aggregate) standData[, flagObservationStatus := "I"] standData[, flagMethod := "s"] setcolorder(standData, c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemSuaFbs", "timePointYears", "Value", "flagObservationStatus", "flagMethod")) # Remove NA Values standData <- standData[!is.na(Value),] standData=standData[measuredElementSuaFbs%in%c(elemKeys,"664","674","684")] areaKeys=areaKeys if("1248"%in%areaKeys){ areaKeys=c(areaKeys,"156") } elemKeys="511" key = DatasetKey(domain = "population", dataset = "population_unpd", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = elemKeys), timePointYears = Dimension(name = "timePointYears", keys = as.character(yearVals)) )) popSWS=GetData(key) popSWS[geographicAreaM49=="156",geographicAreaM49:="1248"] popSWS[,measuredItemSuaFbs:="S2901"] setnames(popSWS,"measuredElement","measuredElementSuaFbs") setcolorder(popSWS,colnames(standData)) standData=data.table(rbind(standData,popSWS)) standData=standData[!(measuredItemSuaFbs%in%c("S2901")& !(measuredElementSuaFbs%in%c("664","674","684","511")))] standData=standData[!(measuredItemSuaFbs%in%c("2903","2941")& !(measuredElementSuaFbs%in%c("664","674","684")))] ############## detects outliers at fbs group level and sends mail if(outlierMail=="Yes"){ balData = subset(standData, measuredElementSuaFbs %in% c("664")) balData = balData[,perc.change:= 100*(Value/shift(Value, type="lead")-1), by=c("geographicAreaM49","measuredItemSuaFbs")] balData = subset(balData, (shift(Value, type="lead")>5 | Value>5) & abs(perc.change)>10 & timePointYears>2013) balData=balData[order(Value,perc.change,timePointYears,decreasing = T)] #balData=nameData("suafbs","fbs_balanced_",balData) bodyFBSGroupOutliers= paste("The Email contains a list of items where the caloric intakes increases more than 10% in abslolute value at FBS group level.", "Consider it as a list of items where to start the validation.", sep='\n') sendMailAttachment(balData,"FBS_BAL_Outliers",bodyFBSGroupOutliers) } ############################ message("Attempting to save standardized data...") setnames(standData, "measuredItemSuaFbs", "measuredItemFbsSua") ptm <- proc.time() out = SaveData(domain = "suafbs", dataset = "fbs_balanced_", data = standData, waitTimeout = 2000000) cat(out$inserted + out$ignored, " observations written and problems with ", out$discarded, sep = "") paste0(out$inserted + out$ignored, " observations written and problems with ", out$discarded) message((proc.time() - ptm)[3]) ################################### ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "Full Standardization and Balancing completed" body = "The plug-in has saved the data in your sessions" if(!CheckDebug()){sendmailR::sendmail(from = from, to = to, subject = subject, msg = body)} paste0("Email sent to ", swsContext.userEmail) <file_sep>/sandbox/elementCodeTesting/codesWithoutItemType.R library(faosws) library(data.table) library(ggplot2) SetClientFiles(dir = "~/R certificate files/QA") GetTestEnvironment( ## baseUrl = "https://hqlprswsas1.hq.un.fao.org:8181/sws", ## token = "<PASSWORD>" baseUrl = "https://hqlqasws1.hq.un.fao.org:8181/sws", token = "<PASSWORD>" ) itemCodes = GetCodeList("agriculture", "agriculture", "measuredItemCPC") missingType = itemCodes[is.na(type), code] key = DatasetKey(domain = "agriculture", dataset = "agriculture", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = GetCodeList("agriculture", "agriculture", "geographicAreaM49")[, code]), measuredElement = Dimension(name = "measuredElement", keys = GetCodeList("agriculture", "agriculture", "measuredElement")[, code]), measuredItemCPC = Dimension(name = "measuredItemCPC", keys = missingType), timePointYears = Dimension(name = "timePointYears", keys = as.character(1950:2015)))) data = GetData(key) data[, .N, c("measuredItemCPC", "measuredElement")] ## Add in trade key = DatasetKey(domain = "trade", dataset = "total_trade_CPC", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = GetCodeList("trade", "total_trade_CPC", "geographicAreaM49")[, code]), measuredElementTrade = Dimension(name = "measuredElementTrade", keys = GetCodeList("trade", "total_trade_CPC", "measuredElementTrade")[, code]), measuredItemCPC = Dimension(name = "measuredItemCPC", keys = missingType), timePointYears = Dimension(name = "timePointYears", keys = as.character(1950:2015)))) tradeData = GetData(key) setnames(tradeData, "measuredElementTrade", "measuredElement") out = rbind(data[, .N, c("measuredItemCPC", "measuredElement")], tradeData[, .N, c("measuredItemCPC", "measuredElement")]) setnames(itemCodes, "code", "measuredItemCPC") out = merge(out, itemCodes[, c("measuredItemCPC", "description"), with = FALSE], by = "measuredItemCPC") <file_sep>/R/addMissingElements.R ##' Add Missing Elements ##' ##' This function takes a data.table and adds rows to it so that the data ##' contains an observation for all elements for each commodity in the dataset. ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' ##' @return The same data.table as what was passed ("data") but possibly with ##' additional rows. ##' @export addMissingElements = function(data, standParams){ ## Data Quality Checks if(nrow(data[, .N, by = c(standParams$yearVar, standParams$geoVar)]) > 1) stop("This function is designed to work with only one country/year at ", "a time!") elements = standParams[c("productionCode", "importCode", "exportCode", "stockCode", "foodCode", "foodProcCode", "feedCode", "wasteCode", "seedCode", "industrialCode", "touristCode", "residualCode")] elements = as.character(elements) fullTable = expand.grid(unique(data[[standParams$itemVar]]), elements) colnames(fullTable) = c(standParams$itemVar, standParams$elementVar) fullTable[[standParams$yearVar]] = data[[standParams$yearVar]][1] fullTable[[standParams$geoVar]] = data[[standParams$geoVar]][1] fullTable = data.table(fullTable) fullTable[, c(standParams$itemVar) := as.character(get(standParams$itemVar))] fullTable[, c(standParams$elementVar) := as.character(get(standParams$elementVar))] data = merge(data, fullTable, by = c(standParams$itemVar, standParams$elementVar, standParams$geoVar, standParams$yearVar), all = TRUE) return(data) } <file_sep>/R/computeSupplyComponents.R ##' Final Standardization to Primary Equivalent ##' ##' After the full SUA has been balanced, all the commodities need to be rolled ##' up to their primary equivalents. This function does this, aggregating up ##' trade and food. ##' ##' @param data The data.table containing the full dataset for standardization. ##' ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param loop just an index of loops ##' ##' @return A data.table with the aggregated primary commodities. ##' @export computeSupplyComponents= function(data, standParams, loop){ ## Pull data about population # start and end year for standardization come from user parameters startYear = as.numeric(swsContext.computationParams$startYear) endYear = as.numeric(swsContext.computationParams$endYear) stopifnot(startYear <= endYear) yearVals = as.character(startYear:endYear) areaKeys = GetCodeList(domain = "suafbs", dataset = "sua", "geographicAreaM49") areaKeys = areaKeys[type == "country", code] # elemKeys="21" # key = DatasetKey(domain = "population", dataset = "population", dimensions = list( # geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), # measuredElementSuaFbs = Dimension(name = "measuredElementPopulation", keys = elemKeys), # timePointYears = Dimension(name = "timePointYears", keys = yearVals) # )) # areaKeys=standData[,unique(geographicAreaM49)] elemKeys="511" key = DatasetKey(domain = "population", dataset = "population_unpd", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = elemKeys), timePointYears = Dimension(name = "timePointYears", keys = as.character(yearVals)) )) pop=GetData(key) pop[geographicAreaM49=="156",geographicAreaM49:="1248"] setnames(pop, "Value", "population") pop=pop[,.(geographicAreaM49,timePointYears, population)] ## Merge pop data with data data=merge(data, pop, by=c("geographicAreaM49","timePointYears"), all.x=TRUE,allow.cartesian = TRUE) ## data[measuredElementSuaFbs=="Calories",DESfoodSupply_kCd:=(Value/365)/(population*1000)] data[measuredElementSuaFbs=="Proteins",proteinSupplyQt_gCd:=(Value/365)/(population*1000)] data[measuredElementSuaFbs=="Fats",fatSupplyQt_gCd:=(Value/365)/(population*1000)] elementsToCreate=c("DESfoodSupply_kCd","proteinSupplyQt_gCd","fatSupplyQt_gCd", "population") nutrients = lapply(elementsToCreate, function(x){ temp=data[,mget(c("geographicAreaM49","timePointYears",x,paste0("fbsID",4-loop+1)))] temp[, Value := get(x)] temp[, c(standParams$elementVar) := x] temp[, c(x) := NULL] temp }) nutrients= rbindlist(nutrients) nutrients=nutrients[!is.na(Value),] data[, c("DESfoodSupply_kCd","proteinSupplyQt_gCd","fatSupplyQt_gCd", "population"):=NULL] nutrients=nutrients[,mget(c("geographicAreaM49","timePointYears","measuredElementSuaFbs",paste0("fbsID", 4-loop+1),"Value"))] out = rbind(data,nutrients) out = unique(out) return(out) } <file_sep>/sandbox/determineElementCodes.R library(faosws) library(faoswsUtil) areaKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", "geographicAreaM49") areaKeys = areaKeys[type == "country", code] elemKeys = GetCodeTree(domain = "agriculture", dataset = "aproduction", "measuredElement") elemKeys = elemKeys[parent %in% c("31", "41", "51", "61", "71", "91", "101", "111", "121", "131"), paste0(children, collapse = ", ")] elemKeys = strsplit(elemKeys, ", ")[[1]] itemKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemKeys = itemKeys[, code] key = DatasetKey(domain = "agriculture", dataset = "aproduction", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = elemKeys), measuredItemSuaFbs = Dimension(name = "measuredItemCPC", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = as.character(2000:2011)) )) data = GetData(key) codeMap = GetTableData(schemaName = "ess", tableName = "item_type_yield_elements") itemKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") setnames(itemKeys, "code", "measuredItemCPC") itemKeys = itemKeys[, c("measuredItemCPC", "type"), with = FALSE] data = merge(data, itemKeys, by = "measuredItemCPC", all.x = TRUE) elemKeys = GetCodeTree(domain = "agriculture", dataset = "aproduction", "measuredElement") elementMap = adjacent2edge(elemKeys) setnames(elementMap, "children", "measuredElement") data = merge(data, elementMap, by = "measuredElement", all.x = TRUE) dcast(data, formula = type ~ parent, value.var = "measuredElement", fun.aggregate = function(x) length(unique(x))) data[, .N, c("measuredElement", "type", "parent")] data[type == "CRPR", .N, c("measuredElement", "type", "parent")][order(as.numeric(parent)), ] write.csv(data[, .N, c("measuredElement", "type", "parent")], file = "~/Desktop/temp.csv", row.names = FALSE) <file_sep>/R/saveFBSItermediateStep.R ##' Save Intermediate steps of Standardization process ##' ##' This function has been created in order to locally save some intermediate ##' steps of the Standardization module. This exigency arose for validation ##' purposes. ##' ##' @param directory Where does the intermediate step have to be saved back to? ##' @param fileName Name of the file we are creating ##' @param data data.table to be saved ##' ##' @export saveFBSItermediateStep=function(directory, fileName, data){ ## Check if the directory specifed in the arguments of the function exists # if(!dir.exists(directory)){ dir.create(directory, recursive = TRUE) # } write.table(data, paste0(directory, "/", fileName,".csv"), sep=";", append=T, col.names = F ,row.names = F) }<file_sep>/R/calculateFoodProc.R ##' calculateFoodProc ##' ##' ##' ##' @param data The data.table containing the full dataset for standardization. ##' It should have columns corresponding to year, country, element, commodity, ##' and value. The specific names of these columns should be in standParams. ##' @param tree The commodity tree which details how elements can be processed ##' into other elements. It does not, however, specify which elements get ##' aggregated into others. This data.table should have columns parent, ##' child, extraction rate, share, and target (target specifying if an element ##' is processed forward or not). Names of these columns should be provided ##' in standParams. ##' ##' @param params The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param availability is availability used for calculation of food processing ##' @param zeroWeight is vector of co-products ##' @return A data.table containing the final balanced and standardized SUA ##' data. Additionally, this table will have new elements in it if ##' nutrientData was provided. ##' ##' @export ##' calculateFoodProc=function(data=data, params=c(), tree=tree,zeroWeight= zeroWeight) { p=params # data[measuredElementSuaFbs==p$productionCode & availability<0 & is.na(Value), Value:=-availability] ##### CRISTINa: trying to ca;culate food proc using production + import # mergeToTree = data[get(params$elementVar)%in% c(params$productionCode,params$importCode)] # mergeToTree = mergeToTree[,Value:=sum(Value,na.rm = TRUE),by=c(params$mergeKey)] # mergeToTree = mergeToTree[,list(measuredItemSuaFbs=get(params$itemVar),Value=Value)] ##### CRISTINa: very bad mergeToTree = data[get(params$elementVar)== params$productionCode,list(measuredItemSuaFbs=get(params$itemVar),Value=Value)] setnames(mergeToTree, params$itemVar, params$childVar) tree = merge(tree, mergeToTree, by = params$childVar, all.x = TRUE) tree[, foodProcElement:= ((Value/extractionRate)*share)*weight] mergeToData=tree[,.(measuredItemSuaFbs=get(params$parentVar), foodProcElement)] if(nrow(mergeToData[!is.na(foodProcElement),])>0){ mergeToData=aggregate(foodProcElement~measuredItemSuaFbs, data=mergeToData, FUN= sum) } mergeToData=data.table(mergeToData) mergeToData=mergeToData[!is.na(foodProcElement),] return(mergeToData) } <file_sep>/modules/supplyChecks/apparConsumption.R ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) library(faoswsStandardization) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/supplyChecks/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } # Value below which supply must fall in order to be a case to be investigated THRESHOLD <- -1000 #startYear = as.numeric(swsContext.computationParams$startYear) #startYear = as.numeric(2014) #endYear = as.numeric(swsContext.computationParams$endYear) #endYear = as.numeric(2016) startYear <- 2010 endYear <- 2017 # TODO: parameterise geoM49 <- swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals <- startYear:endYear ##' Get data configuration and session sessionKey <- swsContext.datasets[[1]] sessionCountries <- getQueryKey("geographicAreaM49", sessionKey) geoKeys <- GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # commodity_table <- ReadDatatable("fbs_commodity_definitions") stopifnot(nrow(commodity_table) > 0) # ##Select the countries based on the user input parameter selectedGEOCode <- switch( geoM49, "session" = sessionCountries, "all" = geoKeys ) ######################################### ##### Pull from SUA unbalanced data ##### ######################################### #message("Pulling SUA Unbalanced Data") # Take geo keys geoDim <- Dimension(name = "geographicAreaM49", keys = selectedGEOCode) # Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredElementSuaFbs")$code eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) # Define item dimension itemKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua")$code itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) # Define the key to pull SUA data key <- DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_data_full <- GetData(key) sua_data <- sua_data_full[ measuredElementSuaFbs %in% c("5510","5610","5910","664") ][ is.na(Value), Value := 0 ][, oldprod := sum(Value[as.numeric(timePointYears) < 2014 & measuredElementSuaFbs == "5510"]), .(geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs) ][, previously_produced := any(oldprod > 0), .(geographicAreaM49, measuredItemFbsSua) ][ #previously_produced == FALSE & timePointYears > 2013 timePointYears > 2013 ][, c("flagObservationStatus","flagMethod") := NULL ] sua_data <- dcast.data.table( sua_data, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value", fill = 0 ) setnames(sua_data, c("5510","5610","5910"), c("production","imports", "exports")) sua_data[, supply := production + imports - exports] ## livestock cpc to exclude livestock <- c("02111","02112","02121.01","02122","02123","02131","02132","02133","02140","02151","02152","02153","02154","02191","02194", "02196","02199.10","02199.20") primary <- commodity_table[primary_commodity == "X", cpc] apparentConsumption <- sua_data[ timePointYears %in% 2014:endYear & !(measuredItemFbsSua %in% livestock) & supply < THRESHOLD & measuredItemFbsSua %in% primary ] #apparentConsumption<- apparentConsumption[,c("geographicAreaM49","measuredItemFbsSua","timePointYears"),with=FALSE] setcolorder(apparentConsumption, c("geographicAreaM49", "measuredItemFbsSua", "timePointYears", "supply", "production", "imports", "exports")) apparentConsumption <- nameData("suafbs", "sua_unbalanced", apparentConsumption, except = "timePointYears") #### send mail bodyApparent <- paste("The Email contains a list of negative apparent consumptions", "at sua unbalanced level. Negative values higher than", THRESHOLD, "have been filtered out.") sendMailAttachment(apparentConsumption, "apparentConsumption", bodyApparent) #apparent consumption is the list of commodities,countries and years where supply is negative. print("Module ran successfully. Check your e-mail.") <file_sep>/R/getOldCommodityTree.R ##' Get Old Commodity Tree ##' ##' This function pulls the old commodity trees from the SWS. These trees are ##' constructed from the extraction rate and shares data from the AUPUS domain. ##' ##' @param geographicAreaFS A character vector containing the geographic area ##' codes in FS format. ##' @param timePointYears A character vector containing the years for which ##' commodity trees are wanted. ##' ##' @return A data.table of the commodity tree. ##' ##' @export ##' getOldCommodityTree = function(geographicAreaFS, timePointYears){ ## Define item and element codes measuredItemFS = GetCodeList(domain = "faostat_one", dataset = "FS1_SUA", dimension = "measuredItemFS")$code extractionElementCode = "41" ## Pull extraction rate data key = DatasetKey(domain = "faostat_one", dataset = "FS1_SUA", dimensions = list( Dimension(name = "geographicAreaFS", keys = geographicAreaFS), Dimension(name = "measuredItemFS", keys = measuredItemFS), Dimension(name = "timePointYears", keys = timePointYears), Dimension(name = "measuredElementFS", keys = extractionElementCode))) extractionRateData = GetData(key) ## Pull share data (defines the shares but also the parent/child ## relationships for the commodity tree) key = DatasetKey(domain = "faostat_one", dataset = "aupus_share_fs", dimensions = list( Dimension(name = "geographicAreaFS", keys = geographicAreaFS), Dimension(name = "measuredItemParentFS", keys = measuredItemFS), Dimension(name = "measuredItemChildFS", keys = measuredItemFS), Dimension(name = "timePointYearsSP", keys = timePointYears))) shareData = GetData(key) # # I don't think we need this, shareData defines the parent/child # # # key = DatasetKey(domain = "faostat_one", dataset = "input_from_proc_fs", # dimensions = list( # Dimension(name = "geographicAreaFS", # keys = geographicAreaFS), # Dimension(name = "measuredItemParentFS", # keys = measuredItemFS), # Dimension(name = "measuredItemChildFS", # keys = measuredItemFS), # Dimension(name = "timePointYearsSP", # keys = timePointYears))) # inputFromProcessingData = GetData(key) setnames(extractionRateData, old = c("measuredItemFS", "timePointYears", "Value", "flagFaostat"), new = c("measuredItemChildFS", "timePointYearsSP", "extractionRate", "flagExtractionRate")) setnames(shareData, old = "Value", new = "share") edges = merge(shareData, extractionRateData, by = c("geographicAreaFS", "measuredItemChildFS", "timePointYearsSP")) ## Format commodity codes with "0"'s and 4 digits edges[, measuredItemParentFS := formatC(as.numeric(measuredItemParentFS), width = 4, flag = "0", format = "d")] edges[, measuredItemChildFS := formatC(as.numeric(measuredItemChildFS), width = 4, flag = "0", format = "d")] edges }<file_sep>/R/adjustCommodityTree.R ##' Adjust Commodity Tree ##' ##' This function takes a set of commodity trees (typically all countries for ##' one year) and adjusts the extraction rates. The rationale is that previous ##' extraction rates were manually adjusted, sometimes to extreme values. ##' Thus, we need a consistent way to modify those rates, and the logic for ##' adjusting those rates is contained in this function. ##' ##' @param commodityTree A data.table containing the edge structure of the ##' commodity tree (specified by parent/child columns) and the extraction ##' rates and shares. Typically, this is produced from getOldCommodityTree. ##' @param parentColname The column name of commodityTree which contains the ##' ID for the parent commodity. ##' @param childColname The column name of commodityTree which contains the ##' ID for the child commodity. ##' @param extractionColname The column name of commodityTree which contains the ##' extraction rates. Extraction rates represent the quantity of the child that ##' can be produced from 1 unit of the parent. Typically, though, they are ##' expressed in 10,000's: i.e. if the extraction rate is 8000, 1 parent unit ##' can be processed into 1 * 8000/10000 = 0.8 child units. ##' @param shareColname The column name of commodityTree which contains the ##' shares variable. This value represents the percent of the parent commodity ##' that is processed into the child. For example, a share value of 50 means ##' that 300 units of the parent would be processed into 300*50/100 = 150 units ##' of the child. ##' @param byKey A character vector of column names of commodityTree. ##' We group extraction rates based on averages across groups. ##' The byKey argument provides the column names which should be used as ##' grouping variables for estimating this mean. Note that parentColname and ##' childColname are always used as grouping variables, as extraction rates are ##' specific to edges. This defaults to NULL, in which case all values (for ##' the same edge) are averaged. ##' @param nSigma The number of standard deviations away from the mean that ##' is deemed acceptable. Any extraction rates outside of this range will be ##' updated based on the estimated mean and standard error. The new extraction ##' rate value will be based on the quantile of the original value. If the ##' original value was the largest value in a group of N extraction rates, then ##' the new value will be the (N-0.5)/N*100 percentile of a normal distribution ##' with mean and variance estimated from the data. If all data should be ##' mapped to the corresponding normal quantile, set nSigma = 0. To just ##' adjust extreme values, set nSigma to something like 2 or 3. Note: this ##' mapping may not preserve the original ordering, and it is only guaranteed ##' to do so if nSigma = 0 (all adjusted) or nSigma = Inf (none adjusted). ##' ##' @return This function returns an object that is the same as the input ##' commodityTree except that extreme extraction rates have been adjusted. ##' ##' @export ##' adjustCommodityTree = function(commodityTree, parentColname = "measuredItemParentFS", childColname = "measuredItemChildFS", extractionColname = "extractionRate", shareColname = "share", byKey = NULL, nSigma){ ## Data Quality Checks stopifnot(is(commodityTree, "data.table")) stopifnot(c(parentColname, childColname, extractionColname, shareColname) %in% colnames(commodityTree)) ## Estimate the mean and variance for each unique year/commodity pair byKey = c(byKey, childColname) ## Overwrite the default huber function so it returns non robust mean/sd ## instead of errors when the MAD (Median Absolute Deviation) can't be ## estimated. commodityTree[, c("meanRate", "sdRate") := huber(y = get(extractionColname), k = nSigma), by = byKey] ## Now, update extreme values with the corresponding value on a normal ## curve (based on their quantiles). commodityTree[, normalScore := (extractionRate - meanRate)/sdRate] ## Subtract 0.5 so that quantiles are at 0.5/N, ..., (N-0.5)/N instead of ## 1/N, 2/N, ..., 1. commodityTree[, extractionQuantile := (rank(normalScore) - .5)/.N, by = byKey] commodityTree[, normalValue := qnorm(extractionQuantile, mean = meanRate, sd = sdRate)] ## Update the extreme values, where "extreme" is defined based on a ## user-provided parameter. # commodityTree[normalScore > nSigma, extractionRate := pmax(0, normalValue)] # commodityTree[normalScore < -nSigma, extractionRate := pmax(0, normalValue)] commodityTree[normalScore > nSigma, extractionRate := pmax(0, meanRate + sdRate*nSigma)] commodityTree[normalScore < -nSigma, extractionRate := pmax(0, meanRate - sdRate*nSigma)] commodityTree[, c("meanRate", "sdRate", "normalScore", "extractionQuantile", "normalValue") := NULL] commodityTree } ##' Wrapper for function from MASS ##' ##' This function is designed to call MASS::huber with two exceptions: missing ##' values are removed and, if MASS::huber results in an error, the non-robust ##' mean/sd are returned. ##' ##' @param y The vector of data. ##' @param ... Additional arguments to pass to MASS::huber ##' ##' @return A numeric vector of length two with the estimated mean and standard ##' deviation. ##' ##' @importFrom MASS huber ##' huber = function(y, ...){ values = try(MASS::huber(y, ...), silent = TRUE) if(is(values, "try-error") | values[2] == 0){ return(list(mu = mean(y, na.rm = TRUE), s = sd(y, na.rm = TRUE))) } return(values) }<file_sep>/R/standardizationWrapper_NW.R ##' FULL STANDARDIZATION PROCESS ##' ##' This function implements the new standardization process. The algorithm is ##' as follows: ##' ##' 1. Any edges with a target of "F" should be immediately "processed forward". ##' This amounts to computing the residual and allocating it to food processing, ##' and, hence, to production of the children of this node. ##' ##' 2. Balance the processed products in the SUA by creating production of ##' processed products. If a node is set to be processed forward, then it is ##' also balanced via a residual (i.e. food processing). ##' ##' 2.1 Since food quantities are now available, we can compute initial calorie ##' estimates. ##' ##' 3. Availability at the "balancing level" (usually primary level, but ##' possibly lower if a node is processed forward or standardized in a different ##' tree) is determined. Note that at this point, all edges designated with an ##' "F" (i.e. forward) will have been removed, and so "balancing level" is the ##' same as the top node of the tree. This availability defines shares for ##' standardization. If no availability of parents is available, the initial ##' shares are used (in tree[, get(standParams$shareVar)]). ##' ##' 4. Standardize commodities according to the commodity tree. This defines ##' the food processing element at balancing level. ##' ##' 5. Balance at the balancing level. ##' ##' 6. Update calories of processed products proportionally based on updated ##' food element values. ##' ##' 7. (only if fbsTree is provided) Sum all commodities up to their FBS level ##' categories. This is the final step to prepare data for FAOSTAT. ##' ##' @param data The data.table containing the full dataset for standardization. ##' It should have columns corresponding to year, country, element, commodity, ##' and value. The specific names of these columns should be in standParams. ##' @param tree The commodity tree which details how elements can be processed ##' into other elements. It does not, however, specify which elements get ##' aggregated into others. This data.table should have columns parent, ##' child, extraction rate, share, and target (target specifying if an element ##' is processed forward or not). Names of these columns should be provided ##' in standParams. ##' @param fbsTree This "tree" should just have three columns: ##' standParams$parentID, standParams$childID, and standParams$extractVar ##' (which if missing will just be assigned all values of 1). This tree ##' specifies how SUA commodities get combined to form the FBS aggregates. If ##' NULL, the last step (aggregation to FBS codes) is skipped and data is ##' simply returned at SUA level. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param nutrientData A data.table containing one column with the item codes ##' (and this column's name must match standParams$itemVar) and additional ##' columns representing nutrient information. For example, you could have 4 ##' columns: measuredItemCPC, calories, proteins, fats. In the calories, ##' proteins, and fats columns there should be numeric values representing ##' multipliers to convert kilograms of the item into calories/proteins/fats. ##' If NULL, nothing is done with nutrients. ##' @param printCodes A list of the item codes which should be printed at each ##' step to show the progress of the algorithm. ##' @param debugFile folder for saving the intermediate files. ##' @param batchnumber Number of batch running. ##' @param utilizationTable Table of utilization for suaFilling ##' @param cutItems tree's cuts ##' @return A data.table containing the final balanced and standardized SUA ##' data. Additionally, this table will have new elements in it if ##' nutrientData was provided. ##' @importFrom faoswsBalancing balancing ##' ##' @export ##' standardizationWrapper_NW = function(data, tree, fbsTree = NULL, standParams, nutrientData = NULL, printCodes = c(), debugFile= NULL,batchnumber=batchnumber, utilizationTable = utilizationTable,cutItems=cutItems ){ data_Stock_Industrial = as.data.frame(data) data_Stock_Industrial = dplyr::select_(data_Stock_Industrial, "measuredItemSuaFbs", "geographicAreaM49", "timePointYears", "classification_feed", "classification_stock", "Median_Value_Stock", "Median_Value_Industrial") data_Stock_Industrial = data_Stock_Industrial[!duplicated(dplyr::select_(data_Stock_Industrial,"geographicAreaM49","measuredItemSuaFbs")),] data = dplyr::select_(data,"-classification_feed","-Median_Value_Stock","-Median_Value_Industrial","-classification_stock") data = as.data.table(data) dataFlags=data.table(data.frame(data)) dataFlags=dataFlags[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","flagObservationStatus","flagMethod"))] data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type","food_classification"))] ## Reassign standParams to p for brevity p = standParams ## STEP 0: Data Quality Checks # Checks for data stopifnot(c(p$geoVar, p$yearVar, p$itemVar, p$elementVar, "Value") %in% colnames(data)) if(!"standardDeviation" %in% colnames(data)) data[, standardDeviation := NA_real_] data[, c(p$geoVar) := as.character(get(p$geoVar))] data[, c(p$yearVar) := as.character(get(p$yearVar))] data[, c(p$itemVar) := as.character(get(p$itemVar))] # Checks for tree stopifnot(c(p$childVar, p$parentVar, p$extractVar, p$targetVar, p$shareVar) %in% colnames(tree)) if(nrow(data[, .N, by = c(p$geoVar, p$yearVar)]) > 1) stop("standardizationWrapper works with one country/year at a time only!") if(any(is.na(tree[, get(p$childVar)]))){ warning("tree has some NA children. Those edges have been deleted.") tree = tree[!is.na(get(p$childVar)), ] } if(!p$standParentVar %in% colnames(tree)){ warning("p$standParentVar is not in the colnames of tree! All ", "commodities will be standardized to the parents that ", "produced them!") tree[, c(p$standParentVar) := NA] } if(!p$standExtractVar %in% colnames(tree)){ warning("p$standExtractVar is not in the colnames of tree! No ", "new extraction rates will be used!") tree[!is.na(get(p$standParentVar)), c(p$standExtractVar) := get(p$extractVar)] } stopifnot(!is.na(tree[, get(p$extractVar)])) ## Check that all standParentVar are NA or a value, never "" stopifnot(tree[!is.na(get(p$standParentVar)), get(p$standParentVar)] != "") # Checks for fbsTree if(!is.null(fbsTree)){ stopifnot(c(p$itemVar, "fbsID1", "fbsID2", "fbsID3", "fbsID4") %in% colnames(fbsTree)) } if(any(is.na(tree[, get(p$parentVar)]))){ warning("tree has some NA parents. Those edges have been deleted.") tree = tree[!is.na(get(p$parentVar)), ] } # Checks for nutrientData if(!is.null(nutrientData)){ if(colnames(nutrientData)[1] != p$itemVar) stop("First column of nutrient data must match standParams$itemVar!") stopifnot(ncol(nutrientData) > 1) # message("Nutrients are assumed to be:", paste(colnames(nutrientData)[-1], collapse = ", ")) geo=nameData(domain = "suafbs", dataset = "fbs_standardized",data.table(geographicAreaM49=data[,unique(get(p$geoVar))])) yea=data[,unique(timePointYears)] message("Country = ",as.character(geo[,2,with=FALSE])," (M49=",as.character(geo[,1,with=FALSE]), ") , year = ",yea) nutrientElements = colnames(nutrientData)[2:ncol(nutrientData)] } else { cat("No nutrient information provided, hence no nutrients are computed.") nutrientElements = c() } message("Download cut Items from SWS...") cutItems=ReadDatatable("cut_items2")[,cpc_code] ## STEP 1: Add missing element codes for commodities that are in the data ## (so that we can print it). Then, print the table! ## Note that this function has been repeted juast after the processForward ## because missingElements have to be created for those children which were not in ## dataset previuosly #for saving the TREE yearT=data[,unique(timePointYears)] data = addMissingElements(data, p) data2keep=data.table(data.frame(data)) setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") if(length(printCodes) > 0){ cat("sua_unbalanced") old = copy(data[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data, standParams = p, printCodes = printCodes) } data=data.table(data.frame(data2keep)) data = addMissingElements(data, p) ### STEP2 Initial Sua Filling if(dim(tree)[1]!=0){ level = findProcessingLevel(tree, from = p$parentVar, to = p$childVar, aupusParam = p) primaryEl = level[processingLevel == 0, get(p$itemVar)] }else{ primaryEl=c() } ## Add in elements not in the tree, as they are essentially parents nonTreeEl = data[[p$itemVar]] nonTreeEl = nonTreeEl[!nonTreeEl %in% level[[p$itemVar]]] # primaryEl = c(primaryEl, nonTreeEl) data[, ProtectedProd := any(get(standParams$elementVar) == standParams$productionCode & Protected==TRUE), by = c(standParams$itemVar)] data[, ProtectedFood := any(get(standParams$elementVar) == standParams$foodCode & Protected==TRUE), by = c(standParams$itemVar)] data[is.na(ProtectedProd), ProtectedProd :=FALSE] data[is.na(ProtectedFood), ProtectedFood :=FALSE] data=data.table(left_join(data,utilizationTable,by=c("geographicAreaM49","measuredElementSuaFbs","measuredItemSuaFbs"))) data = unique(data) data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% # tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% ungroup() data = as.data.table(data) data=suaFilling_NW(data, p=p, tree=tree, primaryCommodities = primaryEl, debugFile=p$createIntermetiateFile, stockCommodities = stockCommodities, utilizationTable = utilizationTable, imbalanceThreshold = 10,loop1=TRUE) data2keep=data.table(data.frame(data)) setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") if(length(printCodes) > 0){ cat("\n\nsua_unbalanced + production filled (step 1 of suaFilling):") data = markUpdated(new = data, old = old, standParams = p) old = copy(data[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data, standParams = p, printCodes = printCodes) } data=data.table(data.frame(data2keep)) ### STEP 3: Compute availability and SHARE 1 data[, availability := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, 0, ifelse(get(p$elementVar) == p$foodCode, 0, ifelse(get(p$elementVar) == p$foodProcCode, 0, ifelse(get(p$elementVar) == p$feedCode, 0, ifelse(get(p$elementVar) == p$wasteCode, 0, ifelse(get(p$elementVar) == p$seedCode, 0, ifelse(get(p$elementVar) == p$industrialCode, 0, ifelse(get(p$elementVar) == p$touristCode, 0, ifelse(get(p$elementVar) == p$residualCode, 0, 0))))))))))))), by = c(p$mergeKey)] mergeToTree = data[, list(availability = mean(availability)), by = c(p$itemVar)] setnames(mergeToTree, p$itemVar, p$parentVar) plotTree = copy(tree) tree = merge(tree, mergeToTree, by = p$parentVar, all.x = TRUE) #### SHAREs 1 # share are the proportion of availability of each parent # on the total availability by child tree[,availability.child:=availability*get(p$extractVar)] tree[, newShare := availability.child / sum(availability.child, na.rm = TRUE), by = c(params$childVar)] tree[, c(params$shareVar) := ifelse(is.na(newShare), get(params$shareVar), newShare)] # tree[, c("newShare","availability.child", "availability") := NULL] tree[, c("newShare") := NULL] # share are the proportion of availability of each parent # on the total availability by child # if availability is negative # shares are a proportion of the number of child of each parent if(dim(tree)[1]!=0){ freqChild= data.table(table(tree[, get(params$childVar)])) setnames(freqChild, c("V1","N"), c(params$childVar, "freq")) tree=merge(tree, freqChild , by=params$childVar) } ### CRISTINA this function has to be used also when availability is NA tree[availability.child<=0|is.na(availability.child), negShare:=1/freq] # tree[availability.child<=0, availability.child:=0] # because a child can have some positive and negative availabilities # new avail. and shares have to be calculated for all the child # in order to make shares sum at 1 tree[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c(params$childVar)] tree[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree[, newShare := ifelse(tempAvailability==0,negShare, tempAvailability / sum(tempAvailability, na.rm = TRUE)), by = c(params$childVar)] tree[,availability.child:=tempAvailability] tree[,availability:=availability.child] tree[,c("freq","tempAvailability","sumPositiveAvail","negShare","availability.child"):=NULL] tree[, c(params$shareVar) := ifelse(is.na(newShare), get(params$shareVar), newShare)] tree[, newShare := NULL] # weight treeShares=plotTree treeShares=treeShares[!is.na(get(p$shareVar))] setnames(treeShares,"share","oldShare") tree=data.table(left_join(tree,treeShares,by=colnames(treeShares)[c(1:3,5:7)])) tree[, c(params$shareVar) := ifelse(is.na(oldShare), get(params$shareVar), oldShare)] tree[, oldShare := NULL] tree[,weight:=1] tree[measuredItemChildCPC %in% zeroWeight , weight:=0] printTree = data.table(data.frame(tree)) ##################### roundNum = function(x){ if(is.na(x)){ return(x) } initialSign = sign(x) x = abs(x) x=round(x,4) x = x * initialSign x = prettyNum(x, big.mark = ",", scientific = FALSE) return(x) } ############################## printTree[,availability:=ifelse(is.na(availability), "-", sapply(availability, roundNum))] printTree[,share:=round(share,2)] setnames(printTree,"measuredItemChildCPC","measuredItemFbsSua") printTree=nameData("suafbs","sua_unbalanced",printTree) setnames(printTree,c("measuredItemFbsSua","measuredItemFbsSua_description"),c("Child","ChildName")) setnames(printTree,"measuredItemParentCPC","measuredItemFbsSua") printTree=nameData("suafbs","sua_unbalanced",printTree) setnames(printTree,c("measuredItemFbsSua","measuredItemFbsSua_description"),c("Parent","ParentName")) printTree=printTree[Child %in% printCodes, c("Child","ChildName", "Parent","ParentName", p$extractVar, "availability","share","weight"), with = FALSE] printTree[,ChildName:=strtrim(ChildName,20)] printTree[,ParentName:=strtrim(ParentName,20)] if(length(printCodes) > 0){ cat("\n\nAvailability of Parent for Food Processing Calculation = Prod+Imp-Exp | Shares by Child | weight of children:") print(knitr::kable(printTree[Child %in% printCodes, c("Child","ChildName" ,"Parent", "ParentName",p$extractVar, "availability","share","weight"), with = FALSE], align = 'r')) } ### STEP 4: Compute FOOD PROCESSING foodProc=calculateFoodProc(data=data, params=p, tree=tree, zeroWeight=zeroWeight) data=merge(data,foodProc, by="measuredItemSuaFbs", all.x = TRUE) #integrate the food processing in the elements data[measuredElementSuaFbs==p$foodProcCode&!is.na(foodProcElement),Value:=foodProcElement] data[,foodProcElement:=NULL] tree[, c("availability","foodProcElement"):=NULL] data[,c("availability","updateFlag"):=NULL] data2keep=data.table(data.frame(data)) setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") if(length(printCodes) > 0){ cat("\nsua_unbalanced + production + food processing caluclated (step 2 of suaFilling):") data = markUpdated(new = data, old = old, standParams = p) old = copy(data[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data, standParams = p, printCodes = printCodes) } data=data.table(data.frame(data2keep)) ### STEP 5: Execute Sua Filling again with Food processing data[,c("availability","updateFlag"):=NULL] data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% # tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% ungroup() data = as.data.table(data) data=suaFilling_NW(data, p=p, tree=tree, primaryCommodities = primaryEl, debugFile = params$createIntermetiateFile, stockCommodities = stockCommodities, utilizationTable = utilizationTable, imbalanceThreshold = 10,loop1=FALSE) data$newValue[is.na(data$newValue)] = data$Value[is.na(data$newValue)] ### STEP 3: Compute availability and SHARE 2 # Recalculate the imbalance data$Diff = data$Value - data$newValue data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% ungroup() data$Protected[is.na(data$Protected)] = FALSE data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="food"&food_classification=="Food"& ((imbalance_Fix+Value_temp)>0)& (!(Protected==TRUE))& (round(abs(imbalance_Fix),5)>0), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = dplyr::left_join(data,data_Stock_Industrial, by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% fill(classification_feed,.direction="up") %>% fill(classification_feed,.direction="down") %>% fill(classification_stock,.direction="up") %>% fill(classification_stock,.direction="down") %>% ungroup() data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data$imbalance_Fix[is.na(data$imbalance_Fix)] = 0 # We will first fix the balance for those feed-only items and then recalculate the imbalance data$Official[is.na(data$Official)] = FALSE # work here! data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="feed"&classification_feed=="feedOnly"& ((imbalance_Fix+Value_temp)>0)& (!(Official==TRUE))& (round(abs(imbalance_Fix),5)>0), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data$imbalance_Fix[is.na(data$imbalance_Fix)] = 0 data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="industrial"& ((imbalance_Fix+Value_temp)>0)& (!(Official==TRUE))& (round(imbalance_Fix,2)<0)& (abs(Median_Value_Industrial)>.1), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data_temp1 = data %>% dplyr::filter(measuredElementSuaFbs=="industrial") %>% group_by(measuredItemSuaFbs,measuredElementSuaFbs,geographicAreaM49,timePointYears) %>% dplyr::mutate(industrialValue = round(Value,2)) %>% dplyr::select_("-Value") %>% ungroup() # data_temp1$industrialValue[data_temp1$Protected==TRUE&(!is.na(data_temp1$Protected))] = NA data_temp2 = data %>% dplyr::filter(measuredElementSuaFbs=="stockChange") %>% dplyr::mutate(StockChangeValue = round(Value,2)) %>% dplyr::select_("-Value") %>% ungroup() # data_temp2$StockChangeValue[data_temp2$Protected==TRUE(!is.na(data_temp2$Protected))] = NA data = dplyr::left_join(data,dplyr::select_(data_temp1, "geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "industrialValue"), by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) data = dplyr::left_join(data,dplyr::select_(data_temp2, "geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "StockChangeValue"), by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) rm(data_temp1) rm(data_temp2) data$industrialValue[is.na(data$industrialValue)&(abs(data$Median_Value_Industrial)>.1)] = 0 # Only activate stocks for those for which existed previously and are primary crops #data$StockChangeValue[is.na(data$StockChangeValue)] = 0 data$Median_Value_Stock[is.na(data$Median_Value_Stock)] = 0 # Set median value stock for non - primaries equal to zero #data$Median_Value_Stock[!(data$type=="CRPR")] = 0 data$Median_Value_Stock[!(data$classification_stock=="Stock_Item")] = 0 data$StockChangeValue[(is.na(data$StockChangeValue)& data$classification_stock=="Stock_Item")] = 0 data$Median_Value_Industrial[is.na(data$Median_Value_Industrial)] = 0 # work here! data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="stockChange"&imbalance_Fix>0, StockChangeValue+imbalance_Fix*(Median_Value_Stock/(Median_Value_Stock+Median_Value_Industrial)),Value)) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="industrial"&imbalance_Fix>0, industrialValue+imbalance_Fix*(Median_Value_Industrial/(Median_Value_Stock+Median_Value_Industrial)),Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="industrial"& (is.nan(Value)|is.na(Value))& imbalance_Fix>0& (abs(Median_Value_Industrial)>.1)&classification_stock=="NonStock"), industrialValue+imbalance_Fix,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"& imbalance_Fix>0& (is.nan(Value)|is.na(Value))& classification_stock=="Stock_Item"), StockChangeValue+imbalance_Fix,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"&is.nan(Value)), StockChangeValue,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="industrial"&is.nan(Value)), industrialValue,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"&imbalance_Fix<0&classification_stock=="Stock_Item"&(!is.na(classification_stock))), StockChangeValue+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Median_Value_Stock","-Median_Value_Industrial","-industrialValue","-StockChangeValue","-imbalance_Fix","-Diff") data = as.data.table(data) # data[, imbalance := sum(ifelse(is.na(Value), 0, Value) * # ifelse(get(p$elementVar) == p$productionCode, 1, # ifelse(get(p$elementVar) == p$importCode, 1, # ifelse(get(p$elementVar) == p$exportCode, -1, # ifelse(get(p$elementVar) == p$stockCode, -1, # ifelse(get(p$elementVar) == p$foodCode, -1, # ifelse(get(p$elementVar) == p$foodProcCode, -1, # ifelse(get(p$elementVar) == p$feedCode, -1, # ifelse(get(p$elementVar) == p$wasteCode, -1, # ifelse(get(p$elementVar) == p$seedCode, -1, # ifelse(get(p$elementVar) == p$industrialCode, -1, # ifelse(get(p$elementVar) == p$touristCode, -1, # ifelse(get(p$elementVar) == p$residualCode, -1, # NA))))))))))))), # by = c(p$mergeKey)] data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% # tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% fill(classification_feed,.direction="up") %>% fill(classification_feed,.direction="down") %>% fill(classification_stock,.direction="up") %>% fill(classification_stock,.direction="down") %>% ungroup() data_type_class = dplyr::select_(data,"geographicAreaM49","measuredItemSuaFbs","timePointYears","type","food_classification") data_type_class = unique(data_type_class) data = dplyr::select_(data,"-classification_feed","-food_classification","-classification_stock") data = as.data.table(data) data=merge(data,foodProc, by="measuredItemSuaFbs", all.x = TRUE) setnames(data,"foodProcElement","availability") if(dim(tree)[1]!=0){ # There's only one availability value per group, but we need an aggregation # function so we use mean. mergeToTree = data[, list(availability = mean(availability)), by = c(p$itemVar)] setnames(mergeToTree, p$itemVar, p$parentVar) # plotTree = copy(tree) tree = merge(tree, mergeToTree, by = p$parentVar, all.x = TRUE) # tree[, availability := NULL] tree[get(standParams$childVar) %in% cutItems, c(standParams$childVar) := paste0("f???_", get(standParams$childVar))] availability = calculateAvailability(tree, p) tree[, availability := NULL] tree = collapseEdges(edges = tree, parentName = p$parentVar, childName = p$childVar, extractionName = p$extractVar, keyCols = NULL) ##### #### CRISTINA adding steps to avoiding multiple lines for each # combination fo parent child due to the fact that # the same combination can happen because a child can be # also a nephew of a commodity # I'm taking mean share, mean ER and only one type tree[,p$extractVar:=mean(get(p$extractVar),na.rm=TRUE),by=c(p$parentVar,p$childVar)] tree[,share:=mean(share,na.rm=TRUE),by=c(p$parentVar,p$childVar)] # tree = tree[,c(1:4),with=FALSE] tree=unique(tree) tree[, target := ifelse(get(p$parentVar) %in% FPCommodities, "F", "B")] tree = merge(tree, itemMap, by = "measuredItemParentCPC") tree[,standParentID:=NA] tree[,weight:=1] tree[get(p$childVar) %in% zeroWeight , weight:=0] ##### tree = merge(tree, availability, by = c(p$childVar, p$parentVar)) tree=calculateShares(data=data, params=p, tree=tree, zeroWeight=zeroWeight) treeShares[get(standParams$childVar) %in% cutItems, c(standParams$childVar) := paste0("f???_", get(standParams$childVar))] # treeShares=treeShares[,c(2,1,3,5,7,4),with=FALSE] treeShares=treeShares[,mget(c("measuredItemChildCPC","measuredItemParentCPC","extractionRate", "target","standParentID","oldShare"))] tree=data.table(left_join(tree,treeShares,by=colnames(treeShares)[c(1:5)])) tree[, c(params$shareVar) := ifelse(is.na(oldShare), get(params$shareVar), oldShare)] tree[, oldShare := NULL] ## STEP 2.1 Compute calories if(!is.null(nutrientData)){ data = merge(data, nutrientData, by = p$itemVar, all.x = TRUE) data[rowSums(is.na(data.table(Calories, Proteins, Fats))) > 0, c("Calories", "Proteins", "Fats") := 0] ## Convert nutrient values into total nutrient info using food ## allocation. ## Please note that we added the multiplicative factor of 10000 because the unit of measurement ## of the nutreient componets is 1/100g sapply(nutrientElements, function(nutrient){ data[, c(nutrient) := (get(nutrient) * Value[get(p$elementVar) == p$foodCode])*10000, by = c(p$itemVar)] }) } data2keep=copy(data.table(data.frame(data))) ##################### setnames(data, "measuredItemSuaFbs", "measuredItemFbsSua") standData=data.table(data.frame(data)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,Calories,Proteins,Fats)] standData = calculateFoodAggregates(standData,p,yearVals) standData=standData[!is.na(measuredElementSuaFbs)] ######### standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua"), variable.name = "measuredElementSuaFbs", value.name = "Value") standDataLong = data.table(data.frame(standDataLong)) standDataLong[,measuredElementSuaFbs:=as.character(measuredElementSuaFbs)] standDataLong=data.table(data.frame(standDataLong)) standDataLong=standDataLong[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") ##################### data2keep2=data.table(data.frame(data)) setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") if(length(printCodes) > 0){ cat("\nsua_balanced:") data = markUpdated(new = data, old = old, standParams = p) old = copy(data[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data, standParams = p, printCodes = printCodes, nutrientElements = "DESfoodSupply_kCd", printProcessing = TRUE) } data=data.table(data.frame(data2keep2)) ##################### # Computing Rice # To express <NAME> in mille equivalent: # 1. Again put the data in wide form ##################### roundNum = function(x){ if(is.na(x)){ return(x) } initialSign = sign(x) x = abs(x) x=round(x,4) x = x * initialSign x = prettyNum(x, big.mark = ",", scientific = FALSE) return(x) } ############################## printTree = data.table(data.frame(tree)) printTree[,availability:=ifelse(is.na(availability), "-", sapply(availability, roundNum))] printTree[,share:=round(share,2)] printTree[,extractionRate:=round(extractionRate,2)] setnames(printTree,"measuredItemChildCPC","measuredItemFbsSua") printTree=nameData("suafbs","sua_unbalanced",printTree) setnames(printTree,c("measuredItemFbsSua","measuredItemFbsSua_description"),c("Child","ChildName")) setnames(printTree,"measuredItemParentCPC","measuredItemFbsSua") printTree=nameData("suafbs","sua_unbalanced",printTree) setnames(printTree,c("measuredItemFbsSua","measuredItemFbsSua_description"),c("Parent","ParentName")) printTree=printTree[Child %in% printCodes, c("Child","ChildName", "Parent","ParentName", p$extractVar, "availability","share","weight"), with = FALSE] printTree[,ChildName:=strtrim(ChildName,20)] printTree[,ParentName:=strtrim(ParentName,20)] if(length(printCodes) > 0){ cat("\n\nAvailability of parents in terms of their children = FoodProc * eR | Final Shares by child:") print(knitr::kable(printTree[Child %in% printCodes, c("Child","ChildName" ,"Parent", "ParentName",p$extractVar, "availability","share","weight"), with = FALSE], align = 'r')) } } ### first intermediate SAVE message("Attempting to save balanced SUA data...") setnames(dataFlags,"measuredItemSuaFbs", "measuredItemFbsSua") standData=data.table(left_join(standDataLong,dataFlags,by=colnames(standDataLong))) standData[is.na(flagObservationStatus), flagObservationStatus := "I"] standData[is.na(flagMethod), flagMethod := "e"] ################### fbs_sua_conversion2 <- data.table(measuredElementSuaFbs=c("Calories", "Fats", "Proteins","DESfoodSupply_kCd","proteinSupplyQt_gCd","fatSupplyQt_gCd", "exports", "feed", "food", "foodManufacturing", "imports", "loss", "production", "seed", "stockChange", "residual","industrial", "tourist"), code=c("261", "281", "271","664","674","684","5910", "5520", "5141", "5023", "5610", "5016", "5510", "5525", "5071", "5166","5165", "5164")) standData = merge(standData, fbs_sua_conversion2, by = "measuredElementSuaFbs") standData = data.table(data.frame(standData)) standData[,`:=`(measuredElementSuaFbs = NULL)] setnames(standData, "code", "measuredElementSuaFbs") standData <- standData[!is.na(Value),] # standData <- standData[,Value:=round(Value,0)] if(!is.null(debugFile)){ saveFBSItermediateStep(directory=paste0(basedir,"/debugFile/Batch_",batchnumber), fileName=paste0("B",batchnumber,"_02_AfterSuaFilling_BeforeST"), data=standData) } ### data=data.table(data.frame(data2keep)) ### ## STEP 4: Standardize commodities to balancing level data = finalStandardizationToPrimary(data = data, tree = tree, standParams = p, sugarHack = FALSE, specificTree = FALSE, cut=cutItems, additiveElements = nutrientElements) # ################################################### data2keep=copy(data.table(data.frame(data))) # ################################################### setnames(data, "measuredItemSuaFbs", "measuredItemFbsSua") data=data.table(data.frame(data)) standDatawide = dcast(data, geographicAreaM49 +timePointYears + measuredItemFbsSua ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua",nutrientElements),variable.name = "measuredElementSuaFbs", value.name = "Value") standDataLong = data.table(data.frame(standDataLong)) standDataLong[,measuredElementSuaFbs:=as.character(measuredElementSuaFbs)] standData=standDataLong[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,Calories,Proteins,Fats)] standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua"),variable.name = "measuredElementSuaFbs", value.name = "Value") ######### standDataLong=data.table(data.frame(standDataLong)) standDataLong=standDataLong[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") #################################################### setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") data0113Print = data[measuredItemSuaFbs!="23161.02"] if(length(printCodes) > 0){ # cat("\nSUA table after standardization (BEFORE PROTECTED CORRECTION:)") cat("\n\nfbs_standardized") data0113Print = markUpdated(new = data0113Print, old = old, standParams = p) old = copy(data0113Print[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data0113Print, standParams = p, printCodes = printCodes, nutrientElements = "DESfoodSupply_kCd", printProcessing = TRUE) } data23610Print = data[measuredItemSuaFbs!="0113"] if(length(printCodes) > 0 & "0113"%in%printCodes){ # cat("\nSUA table after standardization (BEFORE PROTECTED CORRECTION:)") cat("\n\nfbs_standardized with Rice Quantites expressed in Milled equivalent") data23610Print = markUpdated(new = data23610Print, old = old, standParams = p) old = copy(data23610Print[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data23610Print, standParams = p, printCodes = printCodes, nutrientElements = "DESfoodSupply_kCd", printProcessing = TRUE) } #### CRISTINA delete the FoodMAnufacturin rows for the cut items # because these have the code with the prefix f???_ # this generates problems when doing the saving back of the second step. data=copy(data.table(data.frame(data2keep))) data=data[!grepl("f???_",measuredItemSuaFbs)] ############################################################ ### Second intermediate Save message("Attempting to save unbalanced FBS data...") setnames(data, "measuredItemSuaFbs", "measuredItemFbsSua") fbs_sua_conversion <- data.table(measuredElementSuaFbs=c("Calories", "Fats", "Proteins", "exports", "feed", "food", "foodManufacturing", "imports", "loss", "production", "seed", "stockChange", "residual","industrial", "tourist"), code=c("261", "281", "271","5910", "5520", "5141", "5023", "5610", "5016", "5510", "5525", "5071", "5166","5165", "5164")) # standData = merge(data, fbs_sua_conversion, by = "measuredElementSuaFbs") # standData[,`:=`(measuredElementSuaFbs = NULL)] # setnames(standData, "code", "measuredElementSuaFbs") standData=copy(data) standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,Calories,Proteins,Fats)] standData = calculateFoodAggregates(standData,p,yearVals) #### standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua"),variable.name = "measuredElementSuaFbs", value.name = "Value") fbs_sua_conversion2 <- data.table(measuredElementSuaFbs=c("Calories", "Fats", "Proteins","DESfoodSupply_kCd","proteinSupplyQt_gCd","fatSupplyQt_gCd", "exports", "feed", "food", "foodManufacturing", "imports", "loss", "production", "seed", "stockChange", "residual","industrial", "tourist"), code=c("261", "281", "271","664","674","684","5910", "5520", "5141", "5023", "5610", "5016", "5510", "5525", "5071", "5166","5165", "5164")) standData = merge(standDataLong, fbs_sua_conversion2, by = "measuredElementSuaFbs") standData = data.table(data.frame(standData)) standData[,`:=`(measuredElementSuaFbs = NULL)] setnames(standData, "code", "measuredElementSuaFbs") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standData <- standData[!is.na(Value),] ### Cristina Merge with FbsTree for saving only the PrimaryEquivalent CPC codes standData=merge(standData,fbsTree,by.x="measuredItemFbsSua",by.y="measuredItemSuaFbs") ### standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standData[, flagObservationStatus := "I"] standData[, flagMethod := "s"] # standData <- standData[,Value:=round(Value,0)] if(!is.null(debugFile)){ saveFBSItermediateStep(directory=paste0(basedir,"/debugFile/Batch_",batchnumber), fileName=paste0("B",batchnumber,"_03_AfterST_BeforeFBSbal"), data=standData) } setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") #### coutryT=uniqueLevels[i,geographicAreaM49] # save(tree,file=paste0(basedir,"/debugFile/Batch_",batchnumber,"/_tree_",coutryT,"_",yearT,".RData")) ## STEP 5: Balance at the balancing level. data = data[get(p$elementVar) %in% c(p$productionCode, p$importCode, p$exportCode, p$stockCode, p$foodCode, p$feedCode, p$seedCode, p$touristCode, p$industrialCode, p$wasteCode, nutrientElements, p$foodProcCode,p$residualCode), ] data[, nutrientElement := get(p$elementVar) %in% nutrientElements] warning("Not sure how to compute standard deviations! Currently just 10% ", "of value!") data[, standardDeviation := Value * .1] ##Production # data[get(p$elementVar)==p$productionCode, standardDeviation := Value * .01] data[get(p$elementVar)==p$productionCode, standardDeviation := Value * .001] # Batch 119 ##Import data[get(p$elementVar)==p$importCode, standardDeviation := Value * .02] ##Export data[get(p$elementVar)==p$exportCode, standardDeviation := Value * .02] ##Stock data[get(p$elementVar)==p$stockCode, standardDeviation := Value * .25] ##Food data[get(p$elementVar)==p$foodCode, standardDeviation := Value * .025] ##Feed data[get(p$elementVar)==p$feedCode, standardDeviation := Value * .25] ##Seed data[get(p$elementVar)==p$seedCode, standardDeviation := Value * .25] ##Tourist data[get(p$elementVar)==p$touristCode, standardDeviation := Value * .25] ##Industrial data[get(p$elementVar)==p$industrialCode, standardDeviation := Value * .25] ##Waste data[get(p$elementVar)==p$wasteCode, standardDeviation := Value * .25] ##Food processing data[get(p$elementVar)==p$foodProcCode, standardDeviation := Value * .25] data[!get(p$elementVar) %in% nutrientElements, balancedValue := faoswsBalancing::balancing(param1 = sapply(Value, na2zero), param2 = sapply(standardDeviation, na2zero), sign = ifelse(get(p$elementVar) %in% c(p$residualCode),0, ifelse(get(p$elementVar) %in% c(p$productionCode, p$importCode), 1, -1)), lbounds = ifelse(get(p$elementVar) %in% c(p$stockCode, p$touristCode), -Inf, 0), optimize = "constrOptim", constrTol = 1e-6), by = c(p$itemVar)] ## To adjust calories later, compute the ratio for how much food has been ## adjusted by. This looks like a "mean", but really we're just using the ## mean to select the one non-NA element. data[, foodAdjRatio := mean(ifelse(get(p$elementVar) == p$foodCode, balancedValue / Value, NA), na.rm = TRUE), by = c(p$itemVar)] ## The balancedValue will be given for all non-nutrient elements. Update ## all these elements with their balanced values. # NW Here I have intervened again to ensure that only non-official data is changed # The difference is sent to stock change and industrial uses data$Protected[is.na(data$Protected)] = FALSE data$Official[is.na(data$Official)] = FALSE data[!(nutrientElement)&!Protected==TRUE, Value := balancedValue] data$balancedValue[is.na(data$balancedValue)] = data$Value[is.na(data$balancedValue)] data_type_class = distinct(data_type_class,geographicAreaM49,timePointYears,measuredItemSuaFbs,.keep_all = TRUE) data = dplyr::left_join(data,data_type_class,by=c("geographicAreaM49", "timePointYears", "measuredItemSuaFbs")) data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% ungroup() data$Diff = data$Value - data$balancedValue data$Diff[is.na(data$Diff)] = 0 data$Diff = data$Value - data$balancedValue data= as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Diff) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data$Protected[is.na(data$Protected)] = FALSE data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="food"&food_classification=="Food"& ((imbalance_Fix+Value_temp)>0)& (!(Protected==TRUE))& (round(abs(imbalance_Fix),5)>0), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(type,.direction="up") %>% fill(type,.direction="down") %>% fill(food_classification,.direction="up") %>% fill(food_classification,.direction="down") %>% ungroup() data$Protected[is.na(data$Protected)] = FALSE data$Official[is.na(data$Protected)] = FALSE data = dplyr::left_join(data,data_Stock_Industrial, by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% tidyr::complete(measuredElementSuaFbs,nesting(geographicAreaM49,measuredItemSuaFbs,timePointYears))%>% fill(classification_feed,.direction="up") %>% fill(classification_feed,.direction="down") %>% fill(classification_stock,.direction="up") %>% fill(classification_stock,.direction="down") %>% ungroup() data$Diff = data$Value - data$balancedValue data$Diff[is.na(data$Diff)] = 0 data$Diff = data$Value - data$balancedValue data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Diff) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] # We will first fix the balance for those feed-only items and then recalculate the imbalance # work here! data$Official[is.na(data$Official)] = FALSE # work here! data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="feed"&classification_feed=="feedOnly"& ((imbalance_Fix+Value_temp)>0)& (!(Official==TRUE))& (round(abs(imbalance_Fix),5)>0), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Diff) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data$imbalance_Fix[is.na(data$imbalance_Fix)] = 0 data$Value_temp = data$Value data$Value_temp[is.na(data$Value_temp)] = 0 data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="industrial"& ((imbalance_Fix+Value_temp)>0)& (!(Official==TRUE))& (round(imbalance_Fix,2)<0)& (abs(Median_Value_Industrial)>.1), Value_temp+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Value_temp") data = as.data.table(data) data[, imbalance_Fix := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(p$elementVar) == p$productionCode, 1, ifelse(get(p$elementVar) == p$importCode, 1, ifelse(get(p$elementVar) == p$exportCode, -1, ifelse(get(p$elementVar) == p$stockCode, -1, ifelse(get(p$elementVar) == p$foodCode, -1, ifelse(get(p$elementVar) == p$foodProcCode, -1, ifelse(get(p$elementVar) == p$feedCode, -1, ifelse(get(p$elementVar) == p$wasteCode, -1, ifelse(get(p$elementVar) == p$seedCode, -1, ifelse(get(p$elementVar) == p$industrialCode, -1, ifelse(get(p$elementVar) == p$touristCode, -1, ifelse(get(p$elementVar) == p$residualCode, -1, 0))))))))))))), by = c(p$mergeKey)] data_temp1 = data %>% dplyr::filter(measuredElementSuaFbs=="industrial") %>% group_by(measuredItemSuaFbs,measuredElementSuaFbs,geographicAreaM49,timePointYears) %>% dplyr::mutate(industrialValue = round(Value,2)) %>% dplyr::select_("-Value") %>% ungroup() # data_temp1$industrialValue[data_temp1$Protected==TRUE&(!is.na(data_temp1$Protected))] = NA data_temp2 = data %>% dplyr::filter(measuredElementSuaFbs=="stockChange") %>% dplyr::mutate(StockChangeValue = round(Value,2)) %>% dplyr::select_("-Value") %>% ungroup() # data_temp2$StockChangeValue[data_temp2$Protected==TRUE(!is.na(data_temp2$Protected))] = NA data = dplyr::left_join(data,dplyr::select_(data_temp1, "geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "industrialValue"), by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) data = dplyr::left_join(data,dplyr::select_(data_temp2, "geographicAreaM49", "measuredItemSuaFbs", "timePointYears", "StockChangeValue"), by=c("geographicAreaM49","measuredItemSuaFbs","timePointYears")) rm(data_temp1) rm(data_temp2) data$industrialValue[is.na(data$industrialValue)&(abs(data$Median_Value_Industrial)>.1)] = 0 # Only activate stocks for those for which existed previously and are primary crops #data$StockChangeValue[is.na(data$StockChangeValue)] = 0 data$Median_Value_Stock[is.na(data$Median_Value_Stock)] = 0 # Set median value stock for non - primaries equal to zero #data$Median_Value_Stock[!(data$type=="CRPR")] = 0 data$Median_Value_Stock[!(data$classification_stock=="Stock_Item")] = 0 data$StockChangeValue[(is.na(data$StockChangeValue)& data$classification_stock=="Stock_Item")] = 0 data$Median_Value_Industrial[is.na(data$Median_Value_Industrial)] = 0 # work here! data = data %>% group_by(geographicAreaM49,measuredItemSuaFbs,timePointYears) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="stockChange"&imbalance_Fix>0, StockChangeValue+imbalance_Fix*(Median_Value_Stock/(Median_Value_Stock+Median_Value_Industrial)),Value)) %>% dplyr::mutate(Value=ifelse(measuredElementSuaFbs=="industrial"&imbalance_Fix>0, industrialValue+imbalance_Fix*(Median_Value_Industrial/(Median_Value_Stock+Median_Value_Industrial)),Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="industrial"& (is.nan(Value)|is.na(Value))& imbalance_Fix>0& (abs(Median_Value_Industrial)>.1)&classification_stock=="NonStock"), industrialValue+imbalance_Fix,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"& imbalance_Fix>0& (is.nan(Value)|is.na(Value))& classification_stock=="Stock_Item"), StockChangeValue+imbalance_Fix,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"&is.nan(Value)), StockChangeValue,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="industrial"&is.nan(Value)), industrialValue,Value)) %>% dplyr::mutate(Value=ifelse((measuredElementSuaFbs=="stockChange"&imbalance_Fix<0&classification_stock=="Stock_Item"&(!is.na(classification_stock))), StockChangeValue+imbalance_Fix,Value)) %>% ungroup() %>% dplyr::select_("-Median_Value_Stock","-Median_Value_Industrial","-industrialValue","-StockChangeValue","-imbalance_Fix","-Diff") data = as.data.table(data) # Recalculate the balances data[!get(p$elementVar) %in% nutrientElements, balancedValue := faoswsBalancing::balancing(param1 = sapply(balancedValue, na2zero), param2 = sapply(standardDeviation, na2zero), sign = ifelse(get(p$elementVar) %in% c(p$residualCode),0, ifelse(get(p$elementVar) %in% c(p$productionCode, p$importCode), 1, -1)), lbounds = ifelse(get(p$elementVar) %in% c(p$stockCode, p$touristCode), -Inf, 0), optimize = "constrOptim", constrTol = 1e-6), by = c(p$itemVar)] data = as.data.table(data) data2keep=data.table(data.frame(data)) ###################!!!!!!!!!!!!!!!!!!!!!!DATA ############################################################################# setnames(data, "measuredItemSuaFbs", "measuredItemFbsSua") standData=data.table(data.frame(data)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,Calories,Proteins,Fats)] standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua"),variable.name = "measuredElementSuaFbs", value.name = "Value") standDataLong = data.table(data.frame(standDataLong)) standDataLong[,unique(measuredElementSuaFbs)] data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") ####################################################### if(length(printCodes) > 0){ cat("\n\nfbs_balanced:") data = markUpdated(new = data, old = old, standParams = p) old = copy(data[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data, standParams = p, printCodes = printCodes, printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data[, updateFlag := NULL] } ## STEP 6: Update calories of processed products proportionally based on ## updated food element values. data=copy(data.table(data.frame(data2keep))) ###################!!!!!!!!!!!!!!!!!!!!!!DATA data[(nutrientElement), Value := ifelse(((!is.na(Value))&is.na(foodAdjRatio)),Value, Value * foodAdjRatio)] data2keep=data.table(data.frame(data)) ###################!!!!!!!!!!!!!!!!!!!!!!DATA #################################################### #################################################### #################################################### #################################################### # CRISTINA 08/03/2018 # Express the final value of Rice in Milled equivalent dataRice=data[measuredItemSuaFbs=="0113"] dataRice[,measuredItemSuaFbs:="23161.02"] dataRice[!(measuredElementSuaFbs%in%c(nutrientElements)),Value:=Value*0.667] data0113 = copy(data.table(data.frame(data))) data23161 = copy(data.table(data.frame(dataRice))) dataBoth=rbind(data0113,data23161) dataNew=dataBoth[measuredItemSuaFbs!="0113"] data2keep=copy(data.table(data.frame(dataNew))) #################################################### #################################################### #################################################### #################################################### ################################################### ################################################### data=data.table(data.frame(copy(dataBoth))) ############################################################################# setnames(data, "measuredItemSuaFbs", "measuredItemFbsSua") standData=data.table(data.frame(data)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, measuredItemFbsSua, timePointYears, Value,Calories,Proteins,Fats)] standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + measuredItemFbsSua + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","measuredItemFbsSua"),variable.name = "measuredElementSuaFbs", value.name = "Value") standDataLong=data.table(data.frame(standDataLong)) data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") ############################################################################# setnames(data,"measuredItemSuaFbs","measuredItemFbsSua") data=nameData("suafbs","sua_unbalanced",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) setnames(data,"measuredItemFbsSua","measuredItemSuaFbs") data0113Print = data[measuredItemSuaFbs!="23161.02"] if(length(printCodes) > 0){ cat("\n\nfbs_balanced with updated nutrient values:") data0113Print = markUpdated(new = data0113Print, old = old, standParams = p) old = copy(data0113Print[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data0113Print, standParams = p, printCodes = printCodes, printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data0113Print[, updateFlag := NULL] } data23610Print = data[measuredItemSuaFbs!="0113"] if(length(printCodes) > 0 & "0113"%in%printCodes){ cat("\n\nfbs_balanced with updated nutrient values and Rice in Milled equivalent:") data23610Print = markUpdated(new = data23610Print, old = old, standParams = p) old = copy(data23610Print[,c(params$mergeKey,params$elementVar,"Value"),with=FALSE]) printSUATableNames(data = data23610Print, standParams = p, printCodes = printCodes, printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data23610Print[, updateFlag := NULL] } data=copy(data.table(data.frame(data2keep))) ###################!!!!!!!!!!!!!!!!!!!!!!DATA data[, c("balancedValue", "nutrientElement", "foodAdjRatio") := NULL] ## STEP 7: Aggregate to FBS Level if(is.null(fbsTree)){ # If no FBS tree, just return SUA-level results return(data) } else { out = computeFbsAggregate(data = data, fbsTree = fbsTree, standParams = p) if(length(printCodes) > 0){ printCodeTable = fbsTree[get(p$itemVar) %in% printCodes, ] # p$mergeKey[p$mergeKey == p$itemVar] = "fbsID4" # p$itemVar = "fbsID4" cat("\n\nFBS Table at first level of aggregation (fbs items):\n") ############################################################################# standData=data.table(data.frame(out[[1]])) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID4, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID4 ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID4","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID4, timePointYears, Value,Calories,Proteins,Fats)] setnames(standData,"fbsID4","measuredItemFbsSua") standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] setnames(standData,"measuredItemFbsSua","fbsID4") standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID4 + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID4"),variable.name = "measuredElementSuaFbs", value.name = "Value") data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) ############################################################################# data2keep2=data.table(data.frame(data)) # setnames(data,"fbsID4","measuredItemSuaFbs") data[,measuredItemFbsSua:=paste0("S",fbsID4)] data=nameData("suafbs","fbs_balanced_",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) data[,measuredItemFbsSua:=NULL] setnames(data,"fbsID4","measuredItemSuaFbs") printSUATableNames(data = data, standParams = p, printCodes = printCodeTable[, fbsID4], printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data=data.table(data.frame(data2keep2)) # p$mergeKey[p$mergeKey == p$itemVar] = "fbsID3" # p$itemVar = "fbsID3" cat("\n\nFBS Table at second level of aggregation (fbs aggregates):\n") ############################################################################# standData=data.table(data.frame(out[[2]])) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID3, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID3 ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID3","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID3, timePointYears, Value,Calories,Proteins,Fats)] setnames(standData,"fbsID3","measuredItemFbsSua") standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] setnames(standData,"measuredItemFbsSua","fbsID3") standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID3 + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID3"),variable.name = "measuredElementSuaFbs", value.name = "Value") data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) ############################################################################# data2keep2=data.table(data.frame(data)) # setnames(data,"fbsID4","measuredItemSuaFbs") data[,measuredItemFbsSua:=paste0("S",fbsID3)] data=nameData("suafbs","fbs_balanced_",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) data[,measuredItemFbsSua:=NULL] setnames(data,"fbsID3","measuredItemSuaFbs") printSUATableNames(data = data, standParams = p, printCodes = printCodeTable[, fbsID3], printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data=data.table(data.frame(data2keep2)) # p$mergeKey[p$mergeKey == p$itemVar] = "fbsID2" # p$itemVar = "fbsID2" cat("\n\nFBS Table at third level of aggregation (fbs macro aggregates):\n") ############################################################################# standData=data.table(data.frame(out[[3]])) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID2, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID2 ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID2","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID2, timePointYears, Value,Calories,Proteins,Fats)] setnames(standData,"fbsID2","measuredItemFbsSua") standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] setnames(standData,"measuredItemFbsSua","fbsID2") standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID2 + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID2"),variable.name = "measuredElementSuaFbs", value.name = "Value") data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) ############################################################################# data2keep2=data.table(data.frame(data)) # setnames(data,"fbsID4","measuredItemSuaFbs") data[,measuredItemFbsSua:=paste0("S",fbsID2)] data=nameData("suafbs","fbs_balanced_",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) data[,measuredItemFbsSua:=NULL] setnames(data,"fbsID2","measuredItemSuaFbs") printSUATableNames(data = data, standParams = p, printCodes = printCodeTable[, fbsID2], printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data=data.table(data.frame(data2keep2)) # p$mergeKey[p$mergeKey == p$itemVar] = "fbsID1" # p$itemVar = "fbsID1" cat("\n\nFBS Table at final level of aggregation (Grand Total):\n") ############################################################################# standData=data.table(data.frame(out[[4]])) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID1, timePointYears, Value)] standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID1 ~ measuredElementSuaFbs,value.var = "Value") standData = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID1","Calories", "Proteins","Fats"),variable.name = "measuredElementSuaFbs", value.name = "Value") standData=data.table(data.frame(standData)) standData=standData[,.(geographicAreaM49, measuredElementSuaFbs, fbsID1, timePointYears, Value,Calories,Proteins,Fats)] setnames(standData,"fbsID1","measuredItemFbsSua") standData = calculateFoodAggregates(standData,p,yearVals) #### standData=standData[!is.na(measuredElementSuaFbs)] setnames(standData,"measuredItemFbsSua","fbsID1") standDatawide = dcast(standData, geographicAreaM49 +timePointYears + fbsID1 + Calories + Proteins + Fats + DESfoodSupply_kCd + proteinSupplyQt_gCd + fatSupplyQt_gCd ~ measuredElementSuaFbs,value.var = "Value") standDataLong = melt(standDatawide,id.vars = c("geographicAreaM49", "timePointYears","fbsID1"),variable.name = "measuredElementSuaFbs", value.name = "Value") data2print=data.table(standDataLong[!(measuredElementSuaFbs%in%c(nutrientElements,"proteinSupplyQt_gCd","fatSupplyQt_gCd"))]) data=data.table(data.frame(data2print)) ############################################################################# data2keep2=data.table(data.frame(data)) # setnames(data,"fbsID4","measuredItemSuaFbs") data[,measuredItemFbsSua:=paste0("S",fbsID1)] data=nameData("suafbs","fbs_balanced_",data,except = c("measuredElementSuaFbs","geographicAreaM49","timePointYears")) data[,measuredItemFbsSua:=NULL] setnames(data,"fbsID1","measuredItemSuaFbs") printSUATableNames(data = data, standParams = p, printCodes = printCodeTable[, fbsID1], printProcessing = TRUE, nutrientElements = "DESfoodSupply_kCd") data=data.table(data.frame(data2keep2)) } ## return(out) } outOut=list() for (i in seq_len(length(out))) { outOut[[i]]= computeSupplyComponents(data=out[[i]], standParams=p,loop=i) } return(outOut) } <file_sep>/R/printSUATableNames.R ##' Print SUA Table with name of commodities ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param printCodes A character vector of the elements of interest. This is ##' required to keep the table from getting to big/unreadable. ##' @param printProcessing Logical. Should food processing also be printed? ##' @param nutrientElements A list of the nutrient codes which should also be ##' printed. ##' ##' @return Nothing is returned, but a table is returned in a nice format to ##' show the current SUA data. ##' ##' @export ##' ## Function for printing the main table printSUATableNames = function(data, standParams, printCodes, printProcessing = TRUE, nutrientElements = c()){ printDT = copy(data) nameDT = data.table(data.frame(printDT[,c("measuredItemSuaFbs","measuredItemFbsSua_description"),with=FALSE])) setnames(nameDT,colnames(nameDT),c("Item","itemName")) nameDT=unique(nameDT[Item%in%printCodes]) nameDT[,itemName:=strtrim(itemName,20)] if(!"updateFlag" %in% colnames(printDT)){ printDT[, updateFlag := FALSE] } printDT = printDT[, c(standParams$mergeKey, standParams$elementVar, "Value", "updateFlag"), with = FALSE] printDT[, c(standParams$elementVar) := paste0("Value_measuredElement_", get(standParams$elementVar))] printDT = printDT[get(standParams$itemVar) %in% printCodes, ] if(nrow(printDT) == 0){ cat("None of the printCode are in the data! Not printing anything...") return(NULL) } fbsElements = c(standParams$productionCode, standParams$feedCode, standParams$seedCode, standParams$wasteCode, standParams$foodCode, standParams$stockCode, standParams$importCode, standParams$exportCode, standParams$foodProcCode, standParams$industrialCode, standParams$touristCode,standParams$residualCode) printDT[, Value := ifelse(is.na(Value), "-", sapply(Value, roundNum))] printDT[(updateFlag), Value := paste0("**", Value, "**")] printDT[, updateFlag := NULL] if(max(printDT[, .N, by = c(standParams$itemVar, standParams$elementVar)]$N) > 1){ warning("More than one record for a unique combination of item/element.", "Collapsing the data by pasting together values!") printDT = dcast(data = printDT, as.formula(paste0(standParams$itemVar, "~", standParams$elementVar)), value.var = "Value", fill = NA, fun.aggregate = function(...){ paste(..., collapse = "-") } ) } else { printDT = dcast(data = printDT, as.formula(paste0(standParams$itemVar, "~", standParams$elementVar)), value.var = "Value", fill = NA) } setnames(printDT, standParams$itemVar,"Item") oldNames = paste0("Value_measuredElement_", fbsElements) nameFilter = oldNames %in% colnames(printDT) setnames(printDT, oldNames[nameFilter], c("Production", "Feed", "Seed", "Loss", "Food", "StockChange", "Imports", "Exports", "Food Processing", "Industrial", "Tourist","Residuals")[nameFilter]) if(printProcessing){ items = c("Item", "Production", "Imports", "Exports", "StockChange", "Food", "Food Processing", "Feed", "Seed", "Tourist", "Industrial", "Loss","Residuals", nutrientElements) } else { fbsElements = fbsElements[fbsElements != standParams$foodProcCode] items = c("Item", "Production", "Imports", "Exports", "StockChange", "Food", "Feed", "Seed", "Tourist", "Industrial", "Loss","Residuals", nutrientElements) } if(length(nutrientElements) > 0){ setnames(printDT, paste0("Value_measuredElement_", nutrientElements), nutrientElements) } sapply(items, function(colName){ if(!colName %in% colnames(printDT)){ printDT[, (colName) := 0] } else { printDT[is.na(get(colName)), c(colName) := "-"] } }) printDT=data.table(left_join(printDT,nameDT,by="Item")) if(length(nutrientElements) > 0){ printDT=printDT[,c("itemName","Item","Production", "Imports","Exports","StockChange", "Food","Food Processing","Feed","Seed","Tourist","Industrial","Loss","Residuals",nutrientElements),with=FALSE] printDT=data.table(printDT) }else{ printDT=printDT[,.(itemName,Item,Production, Imports,Exports,StockChange, Food,`Food Processing`,Feed,Seed,Tourist,Industrial,Loss,Residuals)] } items = c("itemName","Item", "Production", "Imports", "Exports", "StockChange", "Food","Food Processing", "Feed", "Seed", "Tourist", "Industrial", "Loss","Residuals", nutrientElements) out = print(knitr::kable(printDT[, items, with = FALSE], align = 'r')) return(out) } ##' Round numbers ##' ##' Helper function for rounding numbers for display. ##' ##' @param x A number to be nicely formatted. ##' ##' @return The number as a character string, formatted "nicely". ##' roundNum = function(x){ if(is.na(x)){ return(x) } initialSign = sign(x) x = abs(x) # # 1 or 2 digits: multiple of 5. # # 3 digits: multiple of 10. # # 4 to 7 digits: multiple of 100 # # 8+ digits: 4 significant digits. # if(x < 100){ # x = round(x/5, 0)*5 # } else if(x < 1000){ # x = round(x/10)*10 # } else if(x < 10000000){ # x = round(x/100)*100 # } else { # x = formatC(x, digits = 4) # x = as.numeric(x) # } x=round(x,4) x = x * initialSign x = prettyNum(x, big.mark = ",", scientific = FALSE) return(x) }<file_sep>/R/mapCommodityTree.R ##' Map Commodity Tree ##' ##' This function maps the oldCommodityTree (under one commodity code system) ##' into a new commodity tree. It does this by first translating all parents ##' and children in the tree to their new elements. This may create duplicated ##' edges, and in those cases the extraction rates and shares are averaged. ##' ##' @param oldCommodityTree A data.table containing the edge structure of the ##' commodity tree (specified by parent/child columns) and the extraction ##' rates and shares. Typically, this is produced from getOldCommodityTree. ##' @param commodityMap A data.table containing the mapping from the old ##' commodity codes to the new commodity codes. Currently, no other ##' information from this table will be utilized. ##' @param oldColname The column name of commodityMap which contains the IDs ##' for the old commodity codes. ##' @param newColname The column name of commodityMap which contains the IDs ##' for the new commodity codes. ##' @param parentColname The column name of commodityTree which contains the ##' ID for the parent commodity. ##' @param childColname The column name of commodityTree which contains the ##' ID for the child commodity. ##' @param extractionColname The column name of commodityTree which contains the ##' extraction rates. Extraction rates represent the quantity of the child that ##' can be produced from 1 unit of the parent. Typically, though, they are ##' expressed in 10,000's: i.e. if the extraction rate is 8000, 1 parent unit ##' can be processed into 1 * 8000/10000 = 0.8 child units. ##' @param shareColname The column name of commodityTree which contains the ##' shares variable. This value represents the percent of the parent commodity ##' that is processed into the child. For example, a share value of 50 means ##' that 300 units of the parent would be processed into 300*50/100 = 150 units ##' of the child. ##' @param byKey Character vector of column names of oldCommodityTree which ##' should be used in the by argument when averaging the final extraction ##' rates. The new parent and child item codes will always be included, but ##' the user may want to include year, country, etc. if the passed commodity ##' tree has those dimensions. ##' ##' @return A data.table of the new commodity tree. ##' ##' @export ##' mapCommodityTree = function(oldCommodityTree, commodityMap, oldColname, newColname, parentColname = "measuredItemParentFS", childColname = "measuredItemChildFS", extractionColname = "extractionRate", shareColname = "share", byKey = NULL){ ## Data Quality Checks stopifnot(is(oldCommodityTree, "data.table")) stopifnot(is(commodityMap, "data.table")) stopifnot(c(parentColname, childColname, extractionColname, shareColname) %in% colnames(oldCommodityTree)) stopifnot(c(oldColname, newColname) %in% colnames(commodityMap)) ## Convert codes by merging ## Make a copy of commodityMap so as to not overwrite colnames temporaryMap = copy(commodityMap) ## Update the parent to the new code setnames(temporaryMap, old = oldColname, new = parentColname) temporaryMap[, c(parentColname) := as.character(get(parentColname))] oldCommodityTree[, c(parentColname) := as.character(get(parentColname))] oldCommodityTree = merge(oldCommodityTree, temporaryMap, by = parentColname, allow.cartesian = TRUE) ## Capitalize first letter of newColname to be consistent with camelcase newName = gsub("^([[:alpha:]])", "\\U\\1", newColname, perl = TRUE) setnames(oldCommodityTree, newColname, paste0("parent", newName)) ## Update the child to the new code setnames(temporaryMap, old = parentColname, new = childColname) temporaryMap[, c(childColname) := as.character(get(childColname))] oldCommodityTree[, c(childColname) := as.character(get(childColname))] oldCommodityTree = merge(oldCommodityTree, temporaryMap, by = childColname, allow.cartesian = TRUE) setnames(oldCommodityTree, newColname, paste0("child", newName)) parentColname = paste0("parent", newName) childColname = paste0("child", newName) ## Average extraction rates and shares on duplicated edges newCommodityTree = oldCommodityTree[, list(mean(get(extractionColname)), mean(get(shareColname))), by = c(parentColname, childColname, byKey)] setnames(newCommodityTree, old = c("V1", "V2"), new = c(extractionColname, shareColname)) newCommodityTree }<file_sep>/R/convertSugarCodes.R ##' Converts sugar codes 23511.01 and 23512 to 2351f ##' ##' ##' This function harmonize sugar codes. ##' Raw cane and beet sugar are considered as separate codes in some domain, like trade, because sugar raw can be traded ##' as beet raw, cane raw or just raw (23511.01, 23512 or 2351f), ##' but when one has to go from the processed product to the primary product, ##' is not possible to know if a code 2351f has to be standardized to cane or beet, therefore ##' in the standardization process cane and beet have to be considered as a unique code (2351f) ##' This function makes checks and harmonize sugar codes ##' ##' ##' @param data the downloaded data from sua ##' @param p The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @return A data.table with the data fixed for sugar ##' @export ##' convertSugarCodes = function(data){ dataSugar=data.table(data.frame(data[measuredItemSuaFbs %in% c("23511.01","23512","2351f")])) dataSugar[,ValueSugar:=sum(Value*ifelse(measuredItemSuaFbs=="2351f",0,1)),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] sugarComb = dataSugar[, .N, by = c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] ##### dataSugarA ##### # Filter all the rows for which only one row exists filterSugarA=sugarComb[N==1] filterSugarA=filterSugarA[,N:=NULL] dataSugarA=dataSugar[filterSugarA, ,on=c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] # check if some of this rows are not 2351f and change the flag, in that case dataSugarA[measuredItemSuaFbs!="2351f",flagObservationStatus:=ifelse(flagObservationStatus!="I","I",flagObservationStatus)] dataSugarA[measuredItemSuaFbs!="2351f",flagMethod:=ifelse(!(flagMethod%in%c("e","s")),"s",flagMethod)] dataSugarA[,measuredItemSuaFbs:="2351f"] dataSugarA[,ValueSugar:=NULL] ##### dataSugarB ##### filterSugarB=sugarComb[N>1] filterSugarB=filterSugarB[,N:=NULL] dataSugarC=dataSugar[filterSugarB, ,on=c("geographicAreaM49", "timePointYears","measuredElementSuaFbs")] dataSugarC[,s2351f:=max(ValueSugar,Value),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] dataSugarC[,c("Value","ValueSugar"):=NULL] dataSugarC[,Value:=s2351f*ifelse(measuredItemSuaFbs=="2351f",1,0),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] dataSugarB=dataSugarC[Value!=0] ##### dataSugarD ##### sugarComb2=dataSugarB[,.N,by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")][,N:=NULL] dataSugarD=dataSugarC[sugarComb2,,on=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] dataSugarD=data.table(setdiff(dataSugarC,dataSugarD)) if(nrow(dataSugarD)>0){ dataSugarD[,Value:=sum(s2351f*ifelse(measuredItemSuaFbs=="2351f",0,1)),by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")] dataSugarD=unique(dataSugarD,by=c("geographicAreaM49","timePointYears","measuredElementSuaFbs")) dataSugarD[,measuredItemSuaFbs:="2351f"] dataSugarD=dataSugarD[,colnames(dataSugarA),with=FALSE] dataSugarB=dataSugarB[,colnames(dataSugarA),with=FALSE] dataTorBind=rbind(dataSugarA,dataSugarB,dataSugarD) }else{ dataSugarB=dataSugarB[,colnames(dataSugarA),with=FALSE] dataTorBind=rbind(dataSugarA,dataSugarB) } data=data[!(measuredItemSuaFbs %in% c("23511.01","23512","2351f"))] data=rbind(data,dataTorBind) return(data) }<file_sep>/R/getFBSTree.R ##' Get FBS Tree ##' ##' This function creates the tree for aggregation to FBS commodities. ##' ##' @return A data.table object with the FBS tree. ##' ##' @importFrom faoswsUtil fcl2cpc ##' ##' @export ##' getFBSTree = function(){ tree = fread("/home/josh/Documents/Github/faoswsAupus/data/item_tree_final.csv") tree = tree[, list(itemCode, fbsCode)] tree[, measuredItemCPC := faoswsUtil::fcl2cpc(formatC(tree$itemCode, width = 4, flag = "0"))] tree = tree[!is.na(measuredItemCPC), list(measuredItemCPC, fbsCode)] tree = tree[!is.na(fbsCode), ] fbsLevels = fread("~/Documents/Github/faoswsAupus/documentation/annex7.csv") setnames(fbsLevels, paste0("fbsID", 1:4)) tree = merge(fbsLevels, tree, by.x = "fbsID4", by.y = "fbsCode") setcolorder(tree, c("measuredItemCPC", paste0("fbsID", 4:1))) tree }<file_sep>/R/balanceResidual.R ##' Balance Residual ##' ##' This function forces a balance in the passed elements by allocating the ##' imbalance to one element. ##' ##' If supply < utilization, the imbalance is always assigned to production (as ##' trade is generally assumed to be fixed and stock changes are usually 0 and ##' hence also fixed). ##' ##' If supply > utilization, we must choose where to allocate the imbalance. The ##' default variable is food, but for some commodities we could instead use ##' feed, food processing, or industrial. ##' ##' @param data The data.table containing the full dataset for standardization. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @param primaryCommodities Primary level commodities (such as wheat, oranges, ##' sweet potatoes, etc.) should not be balanced at this step but rather by ##' the balancing algorithm. This argument allows the user to specify a ##' character vector with these primary element codes. ##' @param feedCommodities Sometimes excess supply will need to be allocated to ##' some processed product. The default is to place it into food, but this ##' list specifies which elements should allocate such a difference to feed. ##' @param indCommodities Same as feedCommodities, but for commodities where we ##' allocate the difference to industrial utilization. ##' @param foodCommodities if we use the foodCommodities from the Crude Balancing matrix old faostat. ##' @param seedCommodities This list specify which commodities should allocate imbalance to seed. ##' @param stockCommodities This list specify which commodities should allocate imbalance to stock ##' @param lossCommodities This list specify which commodities should allocate imbalance to loss. ##' @param foodProcessCommodities Same as feedCommodities, but for commodities ##' where we allocate the difference to food processing. ##' @param imbalanceThreshold The size that the imbalance must be in order for ##' an adjustment to be made. ##' @param cut these are primary equivalent commodities. ##' @param tree this is the sub tree used in the function. ##' @return Nothing is returned, but the Value column of the passed data.table ##' is updated. ##' balanceResidual = function(data, standParams, feedCommodities = c(), tree=tree, indCommodities = c(), primaryCommodities = c(), stockCommodities = c(), seedCommodities = c(), lossCommodities = c(),foodCommodities =c(), foodProcessCommodities = c(), imbalanceThreshold = 10,cut=c()){ p = standParams ## imbalance calculates, for each commodity, the residual of the FBS equation and ## assigns this amount to each row for that commodity. knownCodes <- unlist(p[c("productionCode", "importCode", "exportCode", "stockCode", "foodCode", "foodProcCode", "feedCode", "wasteCode", "seedCode", "industrialCode", "touristCode", "residualCode")]) ##!! NOTE: It's unclear here why NAs are showing up here and if they should ## be allowable. unknownCodes <- setdiff(na.omit(unique(data[, get(standParams$elementVar)])), knownCodes) if(length(unknownCodes) > 0){ stop(sprintf("Unknown code(s): %s", paste(unknownCodes, collapse = ", "))) } stopifnot(imbalanceThreshold > 0) data[, imbalance := sum(ifelse(is.na(Value), 0, Value) * ifelse(get(standParams$elementVar) == p$productionCode, 1, ifelse(get(standParams$elementVar) == p$importCode, 1, ifelse(get(standParams$elementVar) == p$exportCode, -1, ifelse(get(standParams$elementVar) == p$stockCode, -1, ifelse(get(standParams$elementVar) == p$foodCode, -1, ifelse(get(standParams$elementVar) == p$foodProcCode, 0, ifelse(get(standParams$elementVar) == p$feedCode, -1, ifelse(get(standParams$elementVar) == p$wasteCode, -1, ifelse(get(standParams$elementVar) == p$seedCode, -1, ifelse(get(standParams$elementVar) == p$industrialCode, -1, ifelse(get(standParams$elementVar) == p$touristCode, -1, ifelse(get(standParams$elementVar) == p$residualCode, -1, NA))))))))))))), by = c(standParams$mergeKey)] ##data[, imbalance := sum(ifelse(is.na(Value), 0, Value) * ## ifelse(get(p$elementVar) == p$productionCode, 1, ## ifelse(get(p$elementVar) == p$importCode, 1, ## ifelse(get(p$elementVar) == p$exportCode, -1, ## ifelse(get(p$elementVar) == p$seedCode, -1,0))))), ## by = c(p$mergeKey)] ##data[!is.na(foodProc) & imbalance>0, imbalance:=imbalance-foodProc] data[imbalance>0 & !is.na(foodProcElement), imbalance:=imbalance-foodProcElement] data[, newValue := ifelse(is.na(Value), 0, Value) + imbalance] # I'm a little confused about why flags aren't used here, but it looks like # items where there's a positive values are marked as official ### # CRISTINA: I'm reacttivating the use of flags and I will consider all the # PROTECTED Production values # data[, officialProd := any(get(standParams$elementVar) == standParams$productionCode & # get(standParams$protected)==TRUE), # by = c(standParams$itemVar)] ### data[, officialProd := any(get(standParams$elementVar) == standParams$productionCode & !is.na(Value) & Value > 0), by = c(standParams$itemVar)] data[, officialFood := any(get(standParams$elementVar) == standParams$foodCode & !is.na(Value) & Value > 0), by = c(standParams$itemVar)] # The commodities that have to be crude balanced are the NON PRIMARY TobeBalancedCommodity=list() primaryCommoditiesChildren=list() for(i in seq_len(length(unique(primaryCommodities))) ) { primaryCommoditiesChildren[[i]]=(getChildren( commodityTree = tree, parentColname =params$parentVar, childColname = params$childVar, topNodes =primaryCommodities[i] )) primaryCommoditiesChildren[[i]]=primaryCommoditiesChildren[[i]][primaryCommoditiesChildren[[i]]!=primaryCommodities[i]] if(nrow(data[get(standParams$itemVar) %in% primaryCommoditiesChildren[[i]] , ])==0 | sum(data[get(standParams$itemVar) %in% primaryCommoditiesChildren[[i]] , Value], na.rm = TRUE)==0 ) { TobeBalancedCommodity[[i]]= data.table(primaryCommodities[i]) } TobeBalancedCommodity[[i]]=data.table(NA) } TobeBalanced= rbindlist(TobeBalancedCommodity) TobeBalanced=TobeBalanced[!is.na(TobeBalanced[,V1])] NotTobeBalanced=primaryCommodities[!primaryCommodities %in% TobeBalanced[,V1]] ## Supply > Utilization: assign difference to food, feed, etc. Or, if ## production is official, force a balance by adjusting food, feed, etc. data[(imbalance > imbalanceThreshold & officialProd ) # data[(imbalance > imbalanceThreshold) & (!get(standParams$itemVar) %in% NotTobeBalanced) , ## Remember, data is currently in long format. This condition is ugly, but the idea is ## that Value should be replaced with newValue if the particular row of interest ## corresponds to the food variable and if the commodity should have it's residual ## allocated to food. Likewise, if the row corresponds to feed and if the commodity ## should have it's residual allocated to feed, then Value is updated with newValue. Value := ifelse( (get(standParams$elementVar) == p$feedCode & get(p$itemVar) %in% feedCommodities) | (get(standParams$elementVar) == p$foodProcCode & get(p$itemVar) %in% foodProcessCommodities) | (get(standParams$elementVar) == p$industrialCode & get(p$itemVar) %in% indCommodities) | (get(standParams$elementVar) == p$stockCode & get(p$itemVar) %in% stockCommodities) | (get(standParams$elementVar) == p$wasteCode & get(p$itemVar) %in% lossCommodities) | (get(standParams$elementVar) == p$seedCode & get(p$itemVar) %in% seedCommodities) | #food have been defined outside the Balance Residual function (Cristina) (get(standParams$elementVar) == p$foodCode & get(p$itemVar) %in% foodCommodities), newValue, Value)] ## data[(imbalance > imbalanceThreshold & officialProd ) ## & (!get(standParams$itemVar) %in% primaryCommodities) , ## ## Remember, data is currently in long format. This condition is ugly, but the idea is ## ## that Value should be replaced with newValue if the particular row of interest ## ## corresponds to the food variable and if the commodity should have it's residual ## ## allocated to food. Likewise, if the row corresponds to feed and if the commodity ## ## should have it's residual allocated to feed, then Value is updated with newValue. ## Value := ifelse(get(standParams$elementVar) == p$foodProcCode,newValue, Value)] ## Supply < Utilization data[imbalance < -imbalanceThreshold & !officialProd & (!get(standParams$itemVar) %in% NotTobeBalanced) & get(standParams$elementVar) == p$productionCode , Value := -newValue] data[, c("imbalance", "newValue") := NULL] } <file_sep>/R/elementCodesToNames.R ##' Element Codes to Names ##' ##' This function converts element codes (such as 5510, 5421, ...) into ##' meaningful names (such as "production", "yield", etc.). It only works with ##' the codes defined in a file called elementCodes, which was om the Share drive ##' paste0(R_SWS_SHARE_PATH,"/browningj/") but now is an ad hoc dataTable in the SWS ##' in the AgricultureProduction domain. The tricky part of this function is that ##' the commodity type must be used to correctly choose the element code, as ##' different commodities may use different codes for production, yield, ... ##' ##' @param data The data.table containing the codes to be mapped. It is assumed ##' to have one column with element codes and one column with item codes. ##' @param elementCol The column name of the column with element codes. ##' @param itemCol The column name of the column with item codes. ##' @param standParams A list of parameters (see ##' faoswsStandardization::defaultStandardizationParameters). If supplied, ##' elementCol and itemCol can be NULL. ##' ##' @export ##' ##' @return The passed data.table "data" but with an updated element column ##' (with names instead of codes). ##' elementCodesToNames = function(data, elementCol = NULL, itemCol = NULL, standParams = NULL){ ## Copy data so as to not modify it in place. Note: we can't have this ## function simply modify data in place because it has to merge data with ## other objects. out = copy(data) ## Data quality checks stopifnot(is(out, "data.table")) if((is.null(elementCol) || is.null(itemCol)) && is.null(standParams)){ stop("Must supply either standParams or both itemCol and elementCol!") } if(!is.null(standParams)){ elementCol = standParams$elementVar itemCol = standParams$itemVar } stopifnot(c(elementCol, itemCol) %in% colnames(out)) if("type" %in% colnames(out)){ stop("'type' is in colnames(data), and this function (elementCodesToNames)", " creates a new column with that name. For safety, an error is thrown.") } ## Get the mapping from item code to item type. elementMap = GetCodeList("agriculture", "aproduction", "measuredItemCPC") message("Get Code List ok") #### ADDED for solving the problem of cassava code: CRISTINA elementMap[code=="01520.02",type:="CRPR"] elementMap[code=="39120.18",type:="CRNP"] message("Two types manually added: Cassava and Marc og Grapes. Code of seed EGGS manually changed in the elementcodes table ") #### setnames(elementMap, "code", itemCol) elementMap = elementMap[, c(itemCol, "type"), with = FALSE] out = merge(out, elementMap, by = itemCol, all.x = TRUE) if(any(is.na(out$type))){ failures = out[is.na(type), unique(get(itemCol))] if(length(failures) > 20) failures = failures[1:20] warning(sum(is.na(out$type)), " total item types are missing (of ", nrow(out), " observations).", " Here's some examples:\n", paste(failures, collapse = ", ")) } # Issue #13 - no data for these # These items are missing in the above: # code description # 1: 01219.90 Other leafy or stem vegetables n.e. # 2: 23130.01 Groats, meal and pellets of Wheat # 3: 2351 Raw cane or beet sugar ## Map element codes to names itemCodeKey = ReadDatatable("element_codes") itemCodeKey[, c("description", "factor") := NULL] ## Cheap duct-taped on method for removing all the indigenous and biological ## cattle itemCodeKey = itemCodeKey[order(itemtype, production), ] itemCodeKey[, suffix := paste0("_", seq_len(.N)), by = "itemtype"] itemCodeKey[suffix == "_1", suffix := ""] # warning("All indigenous and biological cattle and poultry have been # removed. This is a bad thing and it would be best to find a way to replace # them. I recommend looking at issue #17") itemCodeKey = itemCodeKey[suffix == "", ] itemCodeKey = melt(data = itemCodeKey, id.vars = c("itemtype", "suffix")) itemCodeKey = itemCodeKey[!is.na(value), ] ## Verify we don't have duplicated codes if(nrow(itemCodeKey[, !"suffix", with = FALSE]) > nrow(unique(itemCodeKey[, !"suffix", with = FALSE]))){ stop("We have 2+ records with the same element code and item type yet", " representing different things (i.e. biological and standard ", "meat). This will cause ambiguity in the data and must be ", "fixed.") } itemCodeKey[, variable := paste0(variable, suffix)] itemCodeKey[, suffix := NULL] setnames(itemCodeKey, c("itemtype", "value"), c("type", elementCol)) itemCodeKey[, c(elementCol) := as.character(get(elementCol))] out = merge(out, itemCodeKey, by = c("type", elementCol), all.x = TRUE) if(any(is.na(out$variable))){ failures = unique(out[is.na(variable), list(get(itemCol), type)]) if(length(failures) > 20) failures = failures[1:20] warning(sum(is.na(out$variable)), " total item types are missing (of ", nrow(out), " observations) and there are ", nrow(failures), " unique missing combinations.") } ## Replace elementCol with the new names: out[, c(elementCol) := variable] out[, c("variable", "type") := NULL] return(out[]) } <file_sep>/R/calculateProcessingShareFBS.R ##' Function to compute Processing sharing: share that identify the quantity of primary availability ##' that it is allocated in different productive processes. ##' ##' Duplication used in Used in faoswsStandardization ##' ##' @param data data table containing all the columns to compute processingSharing ##' @param params defaultProcessedItamParams parameters, object which contains the parameters ##' @param printSharesGraterThan1 logic parameter ##' ##' @export ##' # Modified by NW to include shares greater than one calculateProcessingShareFBS_NW=function(data, printSharesGraterThan1=TRUE, param){ ##Check that data contains all the necessary columns stopifnot(c(param$geoVar, param$yearVar, param$childVar, param$parentVar, param$extractVar, param$shareDownUp ,params$value, param$availVar) %in% colnames(data)) ##data[, processingShare:=(((get(param$value)/get(param$extractVar))*get(param$shareDownUp))/get( param$availVar ))] data[,param$processingShare:= (( get(params$value)/get (param$extractVar) )* get(param$shareDownUp) )/get((param$availVar))] # intervene here *** ## This merge eventually used the processing tree (the tree extracte dby Cristina from) ##data=merge(data,processingTree, by=c("geographicAreaM49", "measuredItemChildCPC", "timePointYears", "measuredItemParentCPC", "extractionRate")) data[processingShare>1.1,PG1:=1 ] data[processingShare==Inf,PG1:=1 ] data[is.na(PG1),PG1:=0 ] ##data[flagObservationStatus=="E" & flagMethod=="h" & get(param$processingShare)>1.02, processingShare:=1] ##if processing share are Inf, it means that the availability is 0, so the share must be zero as well. data[processingShare==Inf,processingShare:=0 ] ## Force the processing share not exceeding 1 # data[processingShare>1,processingShare:=1 ] ##Attempt to use shares coming from the old system, with shares here we mean the share down up (processing shares) ##data[!is.na(pShare), processingShare:=pShare] ##------------------------------------------------------------------------------------------------------- ##Here we should perform an imputation of the imputation on processingShareParamenters=defaultImputationParameters() processingShareParamenters$imputationValueColumn="processingShare" processingShareParamenters$imputationFlagColumn="processingShareFlagObservationStatus" processingShareParamenters$imputationMethodColumn="processingShareFlagMethod" #processingShareParamenters$byKey=c("geographicAreaM49", "measuredItemChildCPC", "measuredItemParentCPC") processingShareParamenters$byKey=c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") processingShareParamenters$estimateNoData=FALSE processingShareParamenters$ensembleModels$defaultExp=NULL ##processingShareParamenters$ensembleModels$defaultLogistic=NULL processingShareParamenters$ensembleModels$defaultLoess=NULL processingShareParamenters$ensembleModels$defaultSpline=NULL processingShareParamenters$ensembleModels$defaultMars=NULL processingShareParamenters$ensembleModels$defaultMixedModel=NULL ##processingShareParamenters$ensembleModels$defaultMovingAverage=NULL ##processingShareParamenters$ensembleModels$defaultArima=NULL ##dataInpute=copy(data) data[,processingShareFlagObservationStatus:="M"] data[,processingShareFlagMethod:="u"] ## I am flagging the just computed flags with a protected flag combination ## in ordert to use them as training set to produce imputations data[!is.na(processingShare),processingShareFlagObservationStatus:="T"] data[!is.na(processingShare),processingShareFlagMethod:="-"] data[processingShare=="NaN", processingShare:=NA_real_] ##Remove series with no data counts = data[, sum(!is.na(processingShare)), by = c(processingShareParamenters$byKey)] counts=counts[V1!=0] counts=counts[,c(param$geoVar, param$childVar, param$parentVar), with=FALSE] data=data[counts, ,on=c(param$geoVar, param$childVar, param$parentVar)] ## impute processingSharing # NOTE: on 20190523 it was decided to replace the ensemble imputation with a # 3-year moving average (actually it was decided before, never implemented). # This may be temporaty or not, thus the structure of this function still # keeps the ensemble framework, though the actual imputation is replaced # (carried out by imputeVariable() is commented. New code goes from # "STARTSMOVAV" to until "ENDMOVAV", so that if can be changed back easily # to ensemble if required. # #data=arrange(data,geographicAreaM49,measuredItemParentCPC,measuredItemChildCPC,timePointYears) #data=imputeVariable(as.data.table(data),processingShareParamenters) # # STARTSMOVAV my_movav <- function(x, order = 3) { # order should be > 2 stopifnot(order >= 3) non_missing <- sum(!is.na(x)) # For cases that have just two non-missing observations order <- ifelse(order > 2 & non_missing == 2, 2, order) if (non_missing == 1) { x[is.na(x)] <- na.omit(x)[1] } else if (non_missing >= order) { n <- 1 while(any(is.na(x)) & n <= 10) { movav <- suppressWarnings(RcppRoll::roll_mean(x, order, fill = 'extend', align = 'right')) movav <- data.table::shift(movav) x[is.na(x)] <- movav[is.na(x)] n <- n + 1 } x <- zoo::na.fill(x, 'extend') } return(x) } data <- data.table(data)[ order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears) ][, processingShare_avg := my_movav(processingShare, order = 3), .(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC) ] data[is.na(processingShare), `:=`(processingShare = processingShare_avg, processingShareFlagObservationStatus = "I", processingShareFlagMethod = "e")] data[, processingShare_avg := NULL] # ENDMOVAV ## CARLO MODIFICATION check if sum of processing share by productive process is less than 1 # to do this i need the zero weight zeros <- as.character(ReadDatatable('zero_weight')[,item_code]) data=data[,weight:=ifelse(measuredItemChildCPC %in% zeros,0,1)] data=data[,processingShareByProcess:=sum(processingShare*weight), by=c("geographicAreaM49","timePointYears","measuredItemParentCPC")] data=data[,excProcShare:=ifelse(processingShareByProcess>1,processingShareByProcess-1,0)] data=data[,allocExcShare:=processingShare/sum(processingShare), by=c("geographicAreaM49","timePointYears","measuredItemParentCPC")] data=data[,processingShare:=processingShare-excProcShare*allocExcShare] data=data[,processingShareByProcess_new:=sum(processingShare*weight), by=c("geographicAreaM49","timePointYears","measuredItemParentCPC")] ## Force the processing share not exceeding 1 data[processingShare>1,processingShare:=1 ] ##------------------------------------------------------------------------------------------------------- return(data) } <file_sep>/modules/aggregateSuaBal/aggregate4EU.R ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to aggregate des figures at SUA balanced level ##' ##' ##' **Inputs:** ##' ##' * sua balanced ##' ##'' **Output:** ##' ##' * csv file attached in mail ## load the library library(readr) library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) library(faoswsStandardization) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/aggregateSuaBal/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) startYear = as.numeric(2010) #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2016) #geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) EU28=c(40, 56, 100, 191, 196, 203, 208, 233, 246, 250, 276, 300, 348, 372, 380, 428, 440, 442, 470, 528, 616, 620, 642, 703, 705, 724, 752, 826) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # # ##Select the countries based on the user input parameter selectedCountries = EU28 selectedGEOCode = as.character(EU28) ######################################### ##### Pull from SUA balanced data ##### ######################################### message("Pulling SUA balanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredElementSuaFbs") eleKeys <-eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_balanced_data = GetData(key) # kcalData <- subset(sua_balanced_data, measuredElementSuaFbs %in% c("664")) kcalData[,6:7]<-NULL kcalData<-kcalData %>% group_by(geographicAreaM49,timePointYears) %>% mutate(totDES=sum(Value,na.rm = T)) ############## GET FISH DATA AND CLEAN fish<-read.csv("C:\\Users\\Delbello.FAODOMAIN\\Documents\\fisheryEU29.csv") setDT(fish) fish[,geographicAreaM49:=fs2m49(as.character(fish$Country))] setnames(fish,old=c("X2014","X2015","X2016"),new=c("2014","2015","2016")) fish[,c("Country","country_name"):=NULL] fishM=melt.data.table(fish,measure.vars = patterns("^2"), value.name = "Value", variable.name="timePointYears") fishM[,measuredElementSuaFbs:="664"] fishM[,measuredItemFbsSua:="9999"] setcolorder(fishM,c("geographicAreaM49", "measuredItemSuaFbs", "measuredElementFbsSua", "timePointYears", "Value1")) setnames(fishM,"Value1","Value") ################### fbsTree<-ReadDatatable("fbs_tree") fbsCodes<-GetCodeList(domain = "suafbs", dataset = "fbs_balanced_", "measuredItemFbsSua") fbsCodes=subset(fbsCodes,grepl("^S",code)) fbsCodes=subset(fbsCodes,grepl("[[:upper:]]\\s",description)) fbsCodes$code<-gsub("^S","",fbsCodes$code) # fbsTree <- merge(fbsTree,fbsCodes,by.x = "id1",by.y = "code") # # kcalData <- merge(kcalData,fbsTree,by.x = "measuredItemFbsSua",by.y = "item_sua_fbs") # # totalDes=kcalData_id[,totDES:=sum(Value, na.rm = T), by=c("geographicAreaM49,timePointYears,id1")] # # #kcalData<-kcalData[,totDES:=sum(Value, na.rm = T), by=c("geographicAreaM49,timePointYears,id1")] agg2<-kcalData[,desAgg2:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id2")] agg1<-kcalData[,desAgg1:=sum(Value, na.rm = T), by=c("geographicAreaM49","timePointYears","id1")] agg2=agg2[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id2","desAgg2"),with=F] agg1=agg1[,c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs","timePointYears","id1","desAgg1"),with=F] agg2[,measuredItemFbsSua:=id2] agg2[,id2:=NULL] setnames(agg2,"desAgg2","Value") agg2=unique(agg2) #prova=subset(prova,id2=="2903" | id2=="2941" ) #agg2<-nameData("suafbs","fbs_balanced_",agg2) agg1[,measuredItemFbsSua:=id1] agg1[,id1:=NULL] setnames(agg1,"desAgg1","Value") agg1=unique(agg1) aggData=rbind(agg1,agg2,fishM) aggData[,Value:=round(Value,0)] aggDataWide = dcast.data.table(setDT(aggData),geographicAreaM49+ measuredItemFbsSua ~timePointYears , fun.aggregate = NULL,value.var = "Value") aggDataWide$measuredItemFbsSua<-gsub("^2","S2",aggDataWide$measuredItemFbsSua) aggDataWide<-nameData("suafbs","fbs_balanced_",aggDataWide) aggDataWide[,measuredItemFbsSua_description:=ifelse(measuredItemFbsSua=="9999","FISHERY",measuredItemFbsSua_description)] aggDataWide[,measuredItemFbsSua_description:=ifelse(measuredItemFbsSua=="S2901","GRAND TOTAL EXCL. FISH",measuredItemFbsSua_description)] aggDataWide[,measuredItemFbsSua_description:=ifelse(measuredItemFbsSua=="S2941","ANIMAL PRODUCTS EXCL. FISH",measuredItemFbsSua_description)] write.csv(aggDataWide,"EU28_toSend.csv",row.names = F) #prova=subset(prova,id2=="2903" | id2=="2941" ) #agg1<-nameData("suafbs","fbs_balanced_",agg1) # # aniVeg[,measuredItemFbsSua:=ifelse(measuredItemFbsSua=="2903","S2903","S2941")] # aniVegWide = dcast.data.table(setDT(aniVeg),geographicAreaM49+ # measuredItemFbsSua ~timePointYears , fun.aggregate = NULL,value.var = "Value") # # toSend=rbind(GTWide,kcalDataWide) # # # # kcalData2 = melt.data.table(totalDES,id.vars = c("geographicAreaM49","measuredElementSuaFbs","measuredItemFbsSua","timePointYears","Value","totDES"), # measure.vars = "totDES") # kcalData2 = dcast.data.table(setDT(kcalData2),geographicAreaM49+measuredItemFbsSua~timePointYears + totDES, fun.aggregate = NULL,value.var = "Value") # # #kcalData<-nameData("suafbs","fbs_balanced",sua_balanced_data) # # # #sua_balanced_data$measuredItemFbsSua <- paste0("'",sua_balanced_data$measuredItemFbsSua,sep = "") # <file_sep>/sandbox/elementCodeTesting/eggWeightNumber.R library(faosws) library(data.table) library(ggplot2) SetClientFiles(dir = "~/R certificate files/QA") GetTestEnvironment( ## baseUrl = "https://hqlprswsas1.hq.un.fao.org:8181/sws", ## token = "<PASSWORD>" baseUrl = "https://hqlqasws1.hq.un.fao.org:8181/sws", token = "<PASSWORD>" ) itemCodes = GetCodeList("agriculture", "agriculture", "measuredItemCPC") eggCodes = itemCodes[type == "EGGW", code] key = DatasetKey(domain = "agriculture", dataset = "agriculture", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = GetCodeList("agriculture", "agriculture", "geographicAreaM49")[, code]), measuredElement = Dimension(name = "measuredElement", keys = c("5510", "5513")), # egg weight and number measuredItemCPC = Dimension(name = "measuredItemCPC", keys = eggCodes), timePointYears = Dimension(name = "timePointYears", keys = as.character(1950:2015)))) data = GetData(key) fun.agg = function(...){ stopifnot(length(...) <= 1) mean(...) } newData = dcast.data.table(data, formula = geographicAreaM49 + measuredItemCPC + timePointYears ~ measuredElement, fun.aggregate = fun.agg, value.var = "Value") setnames(newData, c("5510", "5513"), c("weight", "count")) ## We certainly have some outlying values: newData[, eggWeight := weight / count] qplot(newData[eggWeight < Inf, eggWeight]) newData[eggWeight > 1000 & eggWeight < Inf, ] qplot(newData[eggWeight < 1000, eggWeight]) newData[eggWeight > 10 & eggWeight < 100, ] qplot(newData[eggWeight < 10, eggWeight]) newData[eggWeight > .5 & eggWeight < 10, ] qplot(newData[eggWeight < 1, eggWeight]) qplot(newData[eggWeight < 0.5, eggWeight]) detectOutlier = function(x){ params = MASS::huber(x) mu = params[[1]] sd = params[[2]] return(abs(x-mu) >= 4*sd) } newData[, outlier := detectOutlier(eggWeight), by = measuredItemCPC] ggplot(newData[!(outlier), ]) + facet_wrap( ~ measuredItemCPC, scale = "free") + geom_bar(aes(x = eggWeight)) fit1 = lm(eggWeight ~ 1, data = newData[!is.na(eggWeight) & eggWeight < Inf, ]) fitFull = lm(eggWeight ~ measuredItemCPC + timePointYears + geographicAreaM49, data = newData[!is.na(eggWeight) & eggWeight < Inf, ]) summary(fitFull) # Maybe it's reasonable to use a global average egg weight: step(fitFull) <file_sep>/R/sendMail4shares.R ##' Send email after having checked for shares ##' ##' This function simply snd email to the user, ##' with the result of the check on shares ##' ##' @param tree single subset of the Tree, which means, a subset having all the parent of a single child ##' where the child is an official one. The subset has the characteristis of having shares not summing at 1 ##' ##' @return message with the status of shares ##' ##' @export ##' sendMail4shares=function(tree){ if(dim(tree)[1]>0){ if(any(tree[,share]==0)){ messageSH=paste("Some manually changed shares might have been recaluclated", "because of inconsistencies", " ", "Moreover:", "There are shares = 0", "Consider deleting ER for deleting connections", " ", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "THE ACCHACHED FILE IS JUST FOR EASY CONSULTATION", "DO NOT TRY TO UPLOAD IT IN THE SWS", "GO TO YOUR SESSION AND MAKE CHANGES THERE", "YOU WILL FIND IN THE SESSION ALL THE VALUE CHANGED", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", sep='\n') }else{ messageSH=paste("Some manually changed shares might have been recaluclated", "because of inconsistencies", " ", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", "THE ACCHACHED FILE IS JUST FOR EASY CONSULTATION", "DO NOT TRY TO UPLOAD IT IN THE SWS", "GO TO YOUR SESSION AND MAKE CHANGES THERE", "YOU WILL FIND IN THE SESSION ALL THE VALUE CHANGED", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", sep='\n') } if(!CheckDebug()){ # Create the body of the message FILETYPE = ".csv" CONFIG <- faosws::GetDatasetConfig(swsContext.datasets[[1]]@domain, swsContext.datasets[[1]]@dataset) sessionid <- ifelse(length(swsContext.datasets[[1]]@sessionId), swsContext.datasets[[1]]@sessionId, "core") basename <- sprintf("%s_%s", "ShareCorrections", sessionid) basedir <- tempfile() dir.create(basedir) destfile <- file.path(basedir, paste0(basename, FILETYPE)) # create the csv in a temporary foldes write.csv(tree, destfile, row.names = FALSE) # define on exit strategy on.exit(file.remove(destfile)) zipfile <- paste0(destfile, ".zip") withCallingHandlers(zip(zipfile, destfile, flags = "-j9X"), warning = function(w){ if(grepl("system call failed", w$message)){ stop("The system ran out of memory trying to zip up your data. Consider splitting your request into chunks") } }) on.exit(file.remove(zipfile), add = TRUE) body = paste("Shares have been checked and corrected", " ", messageSH, " ", "Changed Shares are highlighted in your commodity Tree Session" ,sep='\n') sendmailR::sendmail(from = "<EMAIL>", to = swsContext.userEmail, subject = sprintf("Outcome of checks on shares"), msg = list(strsplit(body,"\n")[[1]], sendmailR::mime_part(destfile, name = paste0(basename, FILETYPE) ) ) ) }else{ if(file.exists(paste0("debugFile/Batch_",batchnumber,"/B",batchnumber,"__0_shareCorrections.csv"))){ file.remove(paste0("debugFile/Batch_",batchnumber,"/B",batchnumber,"__0_shareCorrections.csv")) } dir.create(paste0(PARAMS$debugFolder,"/Batch_",batchnumber), showWarnings = FALSE,recursive=TRUE) write.csv(tree, paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"__0_shareCorrections.csv"), row.names = FALSE) return(message(paste0(dim(tree[severity>0])[1]," shares changed"))) } } # else{ # End of case for which flags and/or figures are invalid # if(!CheckDebug()){ # body = paste("Valid shares") # sendmailR::sendmail(from = "<EMAIL>", # to = swsContext.userEmail, # subject = sprintf("Share successfully checked and saved in the session"), # msg = strsplit(body,"\n")[[1]]) # # } # return(message("Valid Shares")) # } } <file_sep>/modules/supplyChecks/apparConsumptionBis.R ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) library(faoswsStandardization) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/supplyChecks/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) #startYear = as.numeric(2014) #endYear = as.numeric(swsContext.computationParams$endYear) #endYear = as.numeric(2016) startYear = 2010 endYear = 2016 geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # # ##Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) ######################################### ##### Pull from SUA unbalanced data ##### ######################################### message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredElementSuaFbs") eleKeys <-eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_data_full = GetData(key, omitna = F) sua_data <- subset(sua_data_full, measuredElementSuaFbs %in% c("5510","5610","5910","664")) sua_data[is.na(Value), Value := 0] sua_data<- sua_data %>% group_by(geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs) %>% mutate(oldprod=sum(Value[timePointYears<2014 & measuredElementSuaFbs=="5510"])) sua_data<- sua_data %>% group_by(geographicAreaM49, measuredItemFbsSua) %>% mutate(keep=any(oldprod>0)) sua_data=as.data.table(sua_data) sua_data <- subset(sua_data, keep==T) sua_data[, c("flagObservationStatus","flagMethod") := NULL] sua_data <- subset(sua_data, timePointYears>2013) sua_data <- dcast.data.table(sua_data, geographicAreaM49 + measuredItemFbsSua + timePointYears ~ measuredElementSuaFbs, value.var = "Value") setnames(sua_data, c("5510","5610","5910"),c("production","imports", "exports")) sua_data[is.na(imports), imports := 0] sua_data[is.na(exports), exports := 0] sua_data[is.na(production), production := 0] sua_data[,supply := production+imports-exports] ## livestock cpc to exclude '%!in%' <- function(x,y)!('%in%'(x,y)) livestock<- c("02111","02112","02121.01","02122","02123","02131","02132","02133","02140","02151","02152","02153","02154","02191","02194", "02196","02199.10","02199.20") #print apparent consumption apparentConsumption <- copy (sua_data) apparentConsumption <- subset(apparentConsumption, timePointYears %in% c(2014:2016)) apparentConsumption <- subset(apparentConsumption, measuredItemFbsSua %!in% livestock) apparentConsumption <- subset(apparentConsumption, supply < -1000 ) apparentConsumption<- apparentConsumption[,c("geographicAreaM49","measuredItemFbsSua","timePointYears"),with=FALSE] apparentConsumption <-nameData("suafbs","sua_unbalanced",apparentConsumption) apparentConsumption[,timePointYears_description := NULL] #### send mail bodyApparent= paste("The Email contains a list of negative apparent consumptions at sua unbalanced level. Negative values higher than -1000 have been filtered out", sep='\n') sendMailAttachment(apparentConsumption,"apparentConsumption",bodyApparent) #apparent consumption is the list of commodities,countries and years where supply is negative. <file_sep>/sandbox/loadDataForTesting.R library(data.table) library(faosws) GetTestEnvironment( baseUrl = "https://hqlprswsas1.hq.un.fao.org:8181/sws", token = "<PASSWORD>" ## baseUrl = "https://hqlqasws1.hq.un.fao.org:8181/sws", ## token = "<PASSWORD>" ) for(file in dir(path = "~/Documents/Github/faoswsStandardization/R/", full.names = TRUE)) source(file) extractionRateData = fread("~/Documents/Github/faoswsStandardization/data/extractionRate2011.csv") shareData = fread("~/Documents/Github/faoswsStandardization/data/shares2011.csv") setnames(extractionRateData, old = c("measuredItemFS", "timePointYears", "Value", "Status"), new = c("measuredItemChildFS", "timePointYearsSP", "extractionRate", "flagExtractionRate")) setnames(shareData, old = "Value", new = "share") commodityTree = merge(shareData, extractionRateData, by = c("geographicAreaFS", "measuredItemChildFS", "timePointYearsSP")) commodityTree[, c("Geographic Area.x", "Year.x", "Year.y") := NULL, with = FALSE] setnames(commodityTree, "Geographic Area.y", "geographicAreaName") setnames(commodityTree, "Item Parent", "itemParentName") setnames(commodityTree, "Item Child", "itemChildName") setnames(commodityTree, "Aupus Required", "aupusRequired") save(commodityTree, file = "~/Documents/Github/faoswsStandardization/data/commodityTree2011.RData") load("~/Documents/Github/faoswsStandardization/data/commodityTree2011.RData") oldCommodityTree = copy(commodityTree) commodityMap = fread("~/Documents/Github/faoswsStandardization/Old_code_and_documentation/Map_HS2FCL/HS2FCL_Valentina.csv", colClasses = rep("character", 7)) setnames(commodityMap, old = colnames(commodityMap), new = c("itemCodeHS2007", "itemNameHS2007", "itemCodeHS2012", "itemNameHS2012", "itemCodeFCL", "itemNameFCL", "bad")) commodityMap[, bad := NULL] commodityMap = commodityMap[, list(itemCodeHS2012, itemCodeFCL)] newColname = "itemCodeHS2012" oldColname = "itemCodeFCL" ## Plot Commodity Trees in FCL plotCommodityTrees( commodityTree = commodityTree[geographicAreaFS == 1 & timePointYearsSP == 2011, ], parentColname = "measuredItemParentFS", childColname = "measuredItemChildFS", extractionColname = "extractionRate", dir = "~/Documents/Github/faoswsStandardization/sandbox/", prefix = "", adjExtractionRates = TRUE) plotCommodityTrees( commodityTree = commodityTree[, mean(extractionRate), by = c("measuredItemParentFS", "measuredItemChildFS")], parentColname = "measuredItemParentFS", childColname = "measuredItemChildFS", extractionColname = "V1", dir = "~/Documents/Github/faoswsStandardization/sandbox/", prefix = "full", adjExtractionRates = TRUE) ## Check that everything works: load("/home/josh/Documents/Github/Working/FBS Example/tradeData.RData") tradeData = tradeData[, sum(Value), by = c("reportingCountryM49", "measuredElementTrade", "measuredItemHS", "timePointYears")] oldCommodityTree[, measuredItemParentFS := formatC(as.numeric(measuredItemParentFS), width = 4, flag = "0", format = "d")] oldCommodityTree[, measuredItemChildFS := formatC(as.numeric(measuredItemChildFS), width = 4, flag = "0", format = "d")] newCommodityTree = mapCommodityTree(oldCommodityTree = oldCommodityTree, commodityMap = commodityMap, oldColname = "itemCodeFCL", newColname = "itemCodeHS2012") tradeData[, measuredItemHS := formatC(as.numeric(measuredItemHS), width = 6, flag = "0", format = "d")] ## Filter trade data to keep it simple (just look at cereals): tradeData = tradeData[grepl("^100", measuredItemHS), ] smallCommodityTree = newCommodityTree[grepl("^100", childItemCodeHS2012) | grepl("^100", parentItemCodeHS2012), ] tradeData[, calorieRate := 100] setnames(tradeData, old = "V1", new = "Value") levels = getCommodityLevel(smallCommodityTree, "parentItemCodeHS2012", "childItemCodeHS2012", "extractionRate", "share") newCommodityTree[, byProductFlag := FALSE] standardizedTrade = tradeData[, standardize(nodeData = .SD, idColname = "measuredItemHS", quantityColname = "Value", calorieRateColname = "calorieRate", commodityTree = copy(newCommodityTree), parentColname = "parentItemCodeHS2012", childColname = "childItemCodeHS2012", extractionColname = "extractionRate", shareColname = "share", targetNodes = levels[level == 0, node], byProductColname = "byProductFlag"), by = c("reportingCountryM49", "timePointYears", "measuredElementTrade")] tradeData standardizedTrade <file_sep>/modules/outliersSuaBal/main.R ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/outlierDetection/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } startYear = 2013 # TODO: parameterise endYear = 2017 # TODO: parameterise geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) # top48FBSCountries<-as.character(top48FBSCountries) # # selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # # ##Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) ######################################### ##### Pull from SUA unbalanced data ##### ######################################### message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredElementSuaFbs") eleKeys <-eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = eleKeys) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) sua_balanced_data = GetData(key) sua_balanced_data <- subset(sua_balanced_data, measuredElementSuaFbs %in% c("664")) sua_balanced_data <- sua_balanced_data[,perc.change:= Value/shift(Value, type="lead")-1, by=c("geographicAreaM49","measuredItemFbsSua","measuredElementSuaFbs")] sua_balanced_data <- subset(sua_balanced_data, (shift(Value, type="lead")>5 | Value>5) & abs(perc.change)>0.1 & timePointYears>2013) sua_balanced_data<-nameData("suafbs","sua_balanced",sua_balanced_data) #sua_balanced_data$measuredItemFbsSua <- paste0("'",sua_balanced_data$measuredItemFbsSua,sep = "") bodySuaBALOutliers= paste("The Email contains a list of items where the caloric intakes increases more than 10% in abslolute value.", "Consider it as a list of items where to start the validation.", sep='\n') sendMailAttachment(sua_balanced_data,"SuaBALOutliers",bodySuaBALOutliers) <file_sep>/R/defaultStandardizationParameters.R ##' Default Standardization Parameters ##' ##' Provides an object which contains the standardization parameters. This ##' allows for easy passing into functions. The meaning of most variables is ##' fairly clear, but a few obscure ones are described below: ##' ##' \itemize{ ##' ##' \item target The column name of the commodity tree data.frame which contains ##' directions on how to process the tree. In particular, this column should be ##' either "B" or "F" (for "backwards" or "forward" processing). Almost ##' everything should be "backwards" standardized, except for some bizarre cases ##' such as sugar. For sugar cane/beets, the quantities should be ##' "standardized" to raw sugar immediately, so the standardization proceedure ##' handles these "F"/"B" cases differently. ##' ##' } ##' ##' @return A list with the standardization parameters. ##' ##' @export ##' defaultStandardizationParameters = function(){ geoVar = "geographicAreaM49" yearVar = "timePointYears" itemVar = "measuredItemCPC" list( geoVar = geoVar, yearVar = yearVar, itemVar = itemVar, elementVar = "measuredElement", mergeKey = c(geoVar, yearVar, itemVar), # For merging with the main data elementPrefix = "Value_measuredElement_", childVar = "childID", parentVar = "parentID", standParentVar = "standParentID", extractVar = "extractionRate", standExtractVar = "standExtractionRate", shareVar = "share", targetVar = "target", productionCode = "production", yieldCode = "yield", areaHarvCode = "areaHarvested", importCode = "imports", exportCode = "exports", stockCode = "stockChange", foodCode = "food", foodProcCode = "foodManufacturing", feedCode = "feed", wasteCode = "loss", seedCode = "seed", industrialCode = "industrial", touristCode = "tourist", residualCode = "residual" ) }<file_sep>/modules/recalculateStocks/main.R ##' # Pull data from different domains to sua ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to recalculate stocks after validation of stocks variation and check if the resulting opening stocks are realistic ##' ##' ##' **Inputs:** ##' ##' * sua unbalanced ##' ##' **Flag assignment:** ##' ##' E e ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) library(faoswsStandardization) library(faoswsFlag) # oldProductionCode = c("51","11","21","131") ## 51: prod, other for animals # foodCode = "5141" # importCode = "5610" # exportCode = "5910" # oldFeedCode = "101" # oldSeedCode = "111" # # #oldLossCode = "121" # lossCode = "5016" # industrialCode = "5165" # touristCode = "100" # suaTouristCode = "5164" # # Convert tourism units to tonnes # # touristConversionFactor = -1/1000 # touristConversionFactor = 1 # # warning("Stocks is change in stocks, not absolute! This needs to be changed") # stocksCode = c("5071","5113") # # ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/recalculateStocks/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) startYear = as.numeric(2014) #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2016) #geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] #' Select the countries based on the user input parameter ##Select the countries based on the user input parameter # selectedGEOCode = # switch(geoM49, # "session" = sessionCountries, # "all" = selectedCountries) selectedGEOCode = sessionCountries ################################################ ##### Harvest from sua ##### ################################################ message("Reading SUA data...") suaData = GetData(sessionKey,omitna=F) ########################################################### ##### calculate historical ratios ##### ########################################################### # # sua_unb<- suaData %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% mutate(Meanold=mean(Value[timePointYears<2014],na.rm=T)) # sua_unb$Meanold[is.na(sua_unb$Meanold)]<-0 # sua_unb$Value[is.na(sua_unb$Value)]<-0 # # # # # ## # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% mutate(prod=sum(Value[measuredElementSuaFbs==5510])) # sua_unb$prod[is.na(sua_unb$prod)]<-0 # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% mutate(imp=sum(Value[measuredElementSuaFbs==5610])) # sua_unb$imp[is.na(sua_unb$imp)]<-0 # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% mutate(exp=sum(Value[measuredElementSuaFbs==5910])) # sua_unb$exp[is.na(sua_unb$exp)]<-0 # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% mutate(supply=prod+imp-exp) # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% mutate(ratio=Value/supply) # sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) ## mutate(pchange2=(Value/lag(Value))-1) stocksvar<-suaData %>% dplyr::filter((measuredElementSuaFbs=="5071" | measuredElementSuaFbs=="5113") & timePointYears>2013) #stocksvar <- stocksvar %>% group_by(geographicAreaM49,measuredItemFbsSua) %>% arrange(timePointYears) %>% mutate(cumstocks=cumsum(Value)) stockswide<- stocksvar %>% dcast(geographicAreaM49+measuredItemFbsSua+timePointYears~measuredElementSuaFbs,value.var="Value") stockswide$`5071`[is.na(stockswide$`5071`)]<-0 stockswide["stocksnew"]<-stockswide["5113"] ########### esum <- function(x,y) mapply("+", x,y) esum2 <- function(x,y) x+y #stockswide <- stockswide %>% group_by(geographicAreaM49,measuredItemFbsSua) %>% mutate(stocksnew=lag(stocksnew)+lag(`5071`)) #stockswide <- stockswide %>% group_by(geographicAreaM49,measuredItemFbsSua) %>% mutate(stocksnew=Reduce(sum, `5071`, init = 0, accumulate = TRUE)[-1]) #stockswide <- stockswide %>% group_by(geographicAreaM49,measuredItemFbsSua) %>% mutate(stocksnew=Reduce(esum, list(lag(stocksnew),lag(`5071`)),accumulate = T)) stockswide <- stockswide %>% dplyr::group_by(geographicAreaM49,measuredItemFbsSua) %>% dplyr::mutate(stocksnew = cumsum(ifelse(is.na(lag(`5071`)), 0, lag(`5071`))) +`5113`[timePointYears==2014]) stockswide <- stockswide %>% dplyr::mutate(changedStock=(abs(`5113`-stocksnew)>10 & stocksnew>0)) stockswide<- stockswide %>% dplyr::filter(changedStock==T) stockswide[,"5113"]<-stockswide[,"stocksnew"] stockswide=as.data.table(stockswide) stockswide[,c("stocksnew","changedStock","5071"):=NULL] stockslong<-melt(stockswide, id=c("geographicAreaM49","measuredItemFbsSua", "timePointYears")) colnames(stockslong)[4]<-"measuredElementSuaFbs" colnames(stockslong)[5]<-"Value" stockslong[,"flagObservationStatus":="E"] stockslong[,"flagMethod":="e"] stockslong[,measuredElementSuaFbs:=as.character(measuredElementSuaFbs)] setcolorder(stockslong, colnames(suaData)) #stockslong<-stockslong[,colnames(suaData)] ################################################################ ##### save data ##### ################################################################ impute=stockslong out<-as.data.table(impute) out$measuredElementSuaFbs<-as.character(out$measuredElementSuaFbs) stats = SaveData(domain = "suafbs", dataset = "sua_unbalanced", data = out, waitTimeout = 2000000) paste0(stats$inserted, " observations written, ", stats$ignored, " weren't updated, ", stats$appended, " were updated, ", stats$discarded, " had problems.") ################################################################ ##### send Email with notification of correct execution ##### ################################################################ ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "Stocks recalculation plug-in has correctly run" body = "The plug-in has saved the SUAs in your session" sendmailR::sendmail(from, to, subject , body) paste0("Email sent to ", swsContext.userEmail) <file_sep>/README.md # New Standardization Methodology This is the **github** repository for the development of the Standardization and Balancing Methodology <file_sep>/R/markUpdated.R ##' Mark Updated Cells ##' ##' This function compares two data.tables for differences. Note that it ##' assumes a very specific structure, as it is intended to be used with the ##' standardization code only. An additional column is placed on the first ##' data.table that is named updateFlag, and it is TRUE if there is a difference ##' and FALSE otherwise. ##' ##' @param data The new data.table with the standardization data. ##' @param old The original data.table with the standardization data. ##' @param standParams The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' ##' @return The same data.table as new but with an additional column. ##' markUpdated = function(new, old, standParams){ old = old[, c(standParams$mergeKey, standParams$elementVar, "Value"), with = FALSE] new = merge(new, old, by = c(standParams$mergeKey, standParams$elementVar), all.x = TRUE, suffixes = c("", ".old")) new = unique(new) new[, updateFlag := !mapply(identical, x = Value, y = Value.old)] new[, Value.old := NULL] return(new) }<file_sep>/R/dataDownloadFix.R ##' Data Download and Fix of sugar Values ##' ##' ##' This function download the data from sua_unbalanced dataset, then harmonize sugar codes. ##' Raw cane and beet sugar are considered as separate codes in some domain, like trade, because sugar raw can be traded ##' as beet raw, cane raw or just raw (23511.01, 23512 or 2351f), ##' but when one has to go from the processed product to the primary product, ##' is not possible to know if a code 2351f has to be standardized to cane or beet, therefore ##' in the standardization process cane and beet have to be considered as a unique code (2351f) ##' This function makes checks and harmonize sugar codes ##' ##' ##' @param key Key with dimensions for data download. ##' @param p The parameters for standardization. These parameters ##' provide information about the columns of data and tree, specifying (for ##' example) which columns should be standardized, which columns represent ##' parents/children, etc. ##' @return A data.table with the data fixed for sugar ##' @export ##' dataDownloadFix = function(key=c(), p = c() ){ data = elementCodesToNames(data = GetData(key), itemCol = "measuredItemFbsSua", elementCol = "measuredElementSuaFbs") setnames(data, "measuredItemFbsSua", "measuredItemSuaFbs") data[measuredElementSuaFbs=="stock_change",measuredElementSuaFbs:="stockChange"] data[measuredElementSuaFbs=="stock",measuredElementSuaFbs:="stockChange"] data=data[timePointYears%in%yearVals] data=data[!is.na(measuredElementSuaFbs)] ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## datas=data[measuredItemSuaFbs %in% c("23511.01","23512","2351f")] datas[measuredElementSuaFbs=="tourist",measuredItemSuaFbs:="2351f"] datas[measuredElementSuaFbs=="stockChange"&geographicAreaM49=="705",measuredItemSuaFbs:="2351f"] datas[measuredElementSuaFbs=="food"&geographicAreaM49%in%c("422","28","308"),measuredItemSuaFbs:="2351f"] datas[,s2351f:=sum(Value* ifelse(measuredElementSuaFbs == "production"&measuredItemSuaFbs=="2351f",1,0),na.rm = TRUE), by=c("geographicAreaM49","timePointYears")] dataTorBind = unique(datas[measuredElementSuaFbs=="production",list(geographicAreaM49,timePointYears,measuredElementSuaFbs,s2351f,flagObservationStatus,flagMethod)]) datas[,s2351f:=NULL] datas=datas[!(measuredItemSuaFbs%in%c("23511.01","23512"))] dataTorBind = dataTorBind[,measuredItemSuaFbs:="2351f"] setnames(dataTorBind,"s2351f","Value") dataTorBind=dataTorBind[,c(7,3,1,2,4:6),with=FALSE] datas=rbind(datas[!measuredElementSuaFbs=="production"],dataTorBind) data=data[!(measuredItemSuaFbs %in% c("23511.01","23512","2351f"))] data=rbind(data,datas) data=data[, list(Value = sum(Value, na.rm = TRUE)), by = c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","flagObservationStatus","flagMethod")] data=left_join(data,flagValidTable,by=c("flagObservationStatus","flagMethod"))%>% data.table data[flagObservationStatus%in%c("","T"),Official:=TRUE] data[is.na(Official),Official:=FALSE] return(data) }<file_sep>/modules/pullDataToSUA_FBS2018/main.R ##' # Pull data from different domains to sua ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to harvest the data from other tables and pull all ##' relevant FBS data into the SUA/FBS domain. It pulls from the following ##' ##' **Inputs:** ##' ##' * Agriculture Production (production, stock, seed, industrial) ##' * Food (food) ##' * Loss (loss) ##' * feed (feed) ##' * stock (stock) ##' * Trade: ##' in november 2017, for urgent purposes, as it was not possible to validate all the new Trade data ##' it has been decided to use: ##' . Old Trade data up to 2013 ##' . New Trade data from 2014 (Trade domain) ##' * Tourist (tourist) ##' ##' **Flag assignment:** ##' ##' | Observation Status Flag | Method Flag| ##' | --- | --- | --- | ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) oldProductionCode = "51" foodCode = "5141" importCode = "5610" exportCode = "5910" oldFeedCode = "101" oldSeedCode = "111" #oldLossCode = "121" lossCode = "5016" industrialCode = "5165" touristCode = "100" suaTouristCode = "5164" # Convert tourism units to tonnes # touristConversionFactor = -1/1000 touristConversionFactor = 1 # warning("Stocks is change in stocks, not absolute! This needs to be changed") stocksCode = "5071" ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/pullDataToSUA_FBS2018/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } startYear = as.numeric(swsContext.computationParams$startYear) endYear = as.numeric(swsContext.computationParams$endYear) geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] ##' Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) ################################################ ##### Harvest from SUA Validated 2015 ##### ################################################ message("Pulling data from SUA Validated 2015") ## if the geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) eleKeys = GetCodeTree(domain = "agriculture", dataset = "aproduction", dimension = "measuredElement") ## Get all children of old codes eleKeys = strsplit(eleKeys[parent %in% c(oldProductionCode, oldFeedCode, oldSeedCode), children], split = ", ") ## Combine with single codes eleDim = Dimension(name = "measuredElement", keys = c(do.call("c", eleKeys) # ,industrialCode )) itemKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "measuredItemCPC")[, code] itemDim = Dimension(name = "measuredItemCPC", keys = itemKeys) timeDim = Dimension(name = "timePointYears", keys = as.character(yearVals)) agKey = DatasetKey(domain = "agriculture", dataset = "aproduction", dimensions = list( geographicAreaM49 = geoDim, measuredElement = eleDim, measuredItemCPC = itemDim, timePointYears = timeDim) ) agData = GetData(agKey) setnames(agData, c("measuredElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from Agricultural Production ##### ################################################ message("Pulling data from Agriculture Production") ## if the geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) eleKeys = GetCodeTree(domain = "agriculture", dataset = "aproduction", dimension = "measuredElement") ## Get all children of old codes eleKeys = strsplit(eleKeys[parent %in% c(oldProductionCode, oldFeedCode, oldSeedCode), children], split = ", ") ## Combine with single codes eleDim = Dimension(name = "measuredElement", keys = c(do.call("c", eleKeys) # ,industrialCode )) itemKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "measuredItemCPC")[, code] itemDim = Dimension(name = "measuredItemCPC", keys = itemKeys) timeDim = Dimension(name = "timePointYears", keys = as.character(yearVals)) agKey = DatasetKey(domain = "agriculture", dataset = "aproduction", dimensions = list( geographicAreaM49 = geoDim, measuredElement = eleDim, measuredItemCPC = itemDim, timePointYears = timeDim) ) agData = GetData(agKey) setnames(agData, c("measuredElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from Industrial ##### ################################################ # temporary solution til codes will be updated message("Pulling data from industrial domain") indEleDim = Dimension(name = "measuredElement", keys = industrialCode) indKey = DatasetKey(domain = "industrialUse", dataset = "industrialusedata", dimensions = list( geographicAreaM49 = geoDim, measuredElement = indEleDim, measuredItemCPC = itemDim, timePointYears = timeDim) ) indData = GetData(indKey) setnames(indData, c("measuredElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from stockdata ##### ################################################ message("Pulling data from Stock domain") stockEleDim = Dimension(name = "measuredElement", keys = stocksCode) stokKey = DatasetKey(domain = "Stock", dataset = "stocksdata", dimensions = list( geographicAreaM49 = geoDim, measuredElement = stockEleDim, measuredItemCPC = itemDim, timePointYears = timeDim) ) stockData = GetData(stokKey) setnames(stockData, c("measuredElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from Food Domain ##### ################################################ message("Pulling data from Food") eleFoodKey=Dimension(name = "measuredElement", keys = foodCode) foodKey = DatasetKey(domain = "food", dataset = "fooddata", dimensions = list( geographicAreaM49 = geoDim, measuredElement = eleFoodKey, measuredItemCPC = itemDim, timePointYears = timeDim) ) foodData = GetData(foodKey) setnames(foodData, c("measuredElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from loss Domain ##### ################################################ message("Pulling data from Loss") eleLossKey=Dimension(name = "measuredElementSuaFbs", keys = lossCode) itemLossKey = GetCodeList(domain = "lossWaste", dataset = "loss", dimension = "measuredItemSuaFbs")[, code] itemLossDim = Dimension(name = "measuredItemSuaFbs", keys = itemLossKey) lossKey = DatasetKey(domain = "lossWaste", dataset = "loss", dimensions = list( geographicAreaM49 = geoDim, measuredElement = eleLossKey, measuredItemCPC = itemLossDim, timePointYears = timeDim) ) lossData = GetData(lossKey) ################################################ ##### Harvest from Tourism Domain ##### ################################################ message("Pulling data from Tourist") eleTourDim = Dimension(name = "tourismElement", keys = touristCode) tourKey = DatasetKey(domain = "tourism", dataset = "tourismprod", dimensions = list( geographicAreaM49 = geoDim, tourismElement = eleTourDim, measuredItemCPC = itemDim, timePointYears = timeDim) ) tourData = GetData(tourKey) tourData[, `:=`(tourismElement = suaTouristCode, Value = Value * touristConversionFactor)] setnames(tourData, c("tourismElement", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Harvest from Trade Domain ##### ################################################ # Before old data until 2013 were copied in the total trade dataset # Data had to be taken from 2 different sources # These lines are now hided because the total trade data are all on 1 dataset. # TRADE HAS TO BE PULLED: # - FROM OLD FAOSTAT UNTIL 2013 # - FROM NEW DATA STARTING FROM 2010 ################################################ # message("Pulling data from Trade UNTIL 2013 (old FAOSTAT)") # # eleTradeDim = Dimension(name = "measuredElementTrade", # keys = c(importCode, exportCode)) # tradeItems <- na.omit(sub("^0+", "", cpc2fcl(unique(itemKeys), returnFirst = TRUE, version = "latest")), waitTimeout = 2000000) # # geoKeysTrade=m492fs(selectedGEOCode) # # geokeysTrade=geoKeysTrade[!is.na(geoKeysTrade)] # # if(2013>=endYear){ # timeTradeDimUp13 = Dimension(name = "timePointYears", keys = as.character(yearVals)) # # ###### Trade UNTIL 2013 (old FAOSTAT) # message("Trade UNTIL 2013 (old FAOSTAT)") # tradeKeyUp13 = DatasetKey( # domain = "faostat_one", dataset = "updated_sua", # dimensions = list( # #user input except curacao, saint martin and former germany # geographicAreaFS= Dimension(name = "geographicAreaFS", keys = setdiff(geokeysTrade, c("279", "534", "280","274","283"))), # measuredItemFS=Dimension(name = "measuredItemFS", keys = tradeItems), # measuredElementFS=Dimension(name = "measuredElementFS", # keys = c( "61", "91")), # timePointYears = timeTradeDimUp13 ), # sessionId = slot(swsContext.datasets[[1]], "sessionId") # ) # # # tradeDataUp13 = GetData(tradeKeyUp13) # # # tradeDataUp13[, `:=`(geographicAreaFS = fs2m49(geographicAreaFS), # measuredItemFS = fcl2cpc(sprintf("%04d", as.numeric(measuredItemFS)), # version = "latest"))] # # # setnames(tradeDataUp13, c("geographicAreaFS","measuredItemFS","measuredElementFS","flagFaostat" ), # c("geographicAreaM49", "measuredItemSuaFbs","measuredElementSuaFbs","flagObservationStatus")) # # tradeDataUp13[, flagMethod := "-"] # # tradeDataUp13[flagObservationStatus %in% c("P", "*", "X"), flagObservationStatus := "T"] # tradeDataUp13[flagObservationStatus %in% c("T", "F"), flagObservationStatus := "E"] # tradeDataUp13[flagObservationStatus %in% c("B", "C", "E"), flagObservationStatus := "I"] # # tradeDataUp13[measuredElementSuaFbs=="91",measuredElementSuaFbs:="5910"] # tradeDataUp13[measuredElementSuaFbs=="61",measuredElementSuaFbs:="5610"] # # tradeData=tradeDataUp13 # # }else{ # ###### Trade FROM 2014 (new Data) # message("Trade FROM 2014 (new Data)") # # timeTradeDimFrom14 = Dimension(name = "timePointYears", keys = as.character(2014:endYear)) # # tradeKeyFrom14 = DatasetKey( # domain = "trade", dataset = "total_trade_cpc_m49", # dimensions = list(geographicAreaM49 = geoDim, # measuredElementTrade = eleTradeDim, # measuredItemCPC = itemDim, # timePointYears = timeTradeDimFrom14) # ) # tradeDataFrom14 = GetData(tradeKeyFrom14) # setnames(tradeDataFrom14, c("measuredElementTrade", "measuredItemCPC"), # c("measuredElementSuaFbs", "measuredItemSuaFbs")) # # ###### Merging Trade Data # message("Merging Data") # if(2013<startYear){ # tradeData=tradeDataFrom14 # }else{ # timeTradeDimUp13 = Dimension(name = "timePointYears", keys = as.character(startYear:2013)) # message("Trade UNTIL 2013 (old FAOSTAT)") # tradeKeyUp13 = DatasetKey( # domain = "faostat_one", dataset = "updated_sua", # dimensions = list( # #user input except curacao, saint martin and former germany # geographicAreaFS= Dimension(name = "geographicAreaFS", keys = setdiff(geokeysTrade, c("279", "534", "280","274","283"))), # measuredItemFS=Dimension(name = "measuredItemFS", keys = tradeItems), # measuredElementFS=Dimension(name = "measuredElementFS", # keys = c( "61", "91")), # timePointYears = timeTradeDimUp13 ), # sessionId = slot(swsContext.datasets[[1]], "sessionId") # ) # # # tradeDataUp13 = GetData(tradeKeyUp13) # # # tradeDataUp13[, `:=`(geographicAreaFS = fs2m49(geographicAreaFS), # measuredItemFS = fcl2cpc(sprintf("%04d", as.numeric(measuredItemFS)), # version = "latest"))] # # # setnames(tradeDataUp13, c("geographicAreaFS","measuredItemFS","measuredElementFS","flagFaostat" ), # c("geographicAreaM49", "measuredItemSuaFbs","measuredElementSuaFbs","flagObservationStatus")) # # tradeDataUp13[, flagMethod := "-"] # # tradeDataUp13[flagObservationStatus %in% c("P", "*", "X"), flagObservationStatus := "T"] # tradeDataUp13[flagObservationStatus %in% c("T", "F"), flagObservationStatus := "E"] # tradeDataUp13[flagObservationStatus %in% c("B", "C", "E"), flagObservationStatus := "I"] # # tradeDataUp13[measuredElementSuaFbs=="91",measuredElementSuaFbs:="5910"] # tradeDataUp13[measuredElementSuaFbs=="61",measuredElementSuaFbs:="5610"] # # tradeData=rbind(tradeDataUp13,tradeDataFrom14) # # } # # } ### TRADE DATA FROM SINGLE SOURCE message("Pulling data from Trade") eleTradeDim = Dimension(name = "measuredElementTrade", keys = c(importCode, exportCode)) tradeItems <- na.omit(sub("^0+", "", cpc2fcl(unique(itemKeys), returnFirst = TRUE, version = "latest")), waitTimeout = 2000000) timeTradeDim = Dimension(name = "timePointYears", keys = as.character(yearVals)) tradeKey = DatasetKey( domain = "trade", dataset = "total_trade_cpc_m49", dimensions = list(geographicAreaM49 = geoDim, measuredElementTrade = eleTradeDim, measuredItemCPC = itemDim, timePointYears = timeTradeDim) ) tradeData = GetData(tradeKey) setnames(tradeData, c("measuredElementTrade", "measuredItemCPC"), c("measuredElementSuaFbs", "measuredItemSuaFbs")) ################################################ ##### Merging data files together ##### ################################################ message("Merging data files together and saving") out = do.call("rbind", list(agData, stockData,foodData, lossData, tradeData, tourData,indData)) #protected data #### CRISTINA: after havig discovered that for crops , official food values are Wrong and have to be deleted. # now we have to delete all the wrong values: # THE FOLLOWING STEPS HAVE BEEN COMMENTED BECAUSE THEY SHOULD NOT BE NEEDED # the data might have to be corrected from the questionnaires cropsOfficialFood = c("0111","0112","0113","0115","0116","0117","01199.02","01801","01802") out[!geographicAreaM49%in%c("604")&measuredItemSuaFbs%in%cropsOfficialFood &measuredElementSuaFbs=="5141" ,Value:=NA] # only for Japan, delete also Food of Rice Milled. out[geographicAreaM49=="392"&measuredElementSuaFbs=="5141"&measuredItemSuaFbs=="23161.02",Value:=0] #### The previous step has been inserted here and removed from the standardization in order # to give to the data team the possibility to eventually add some food value for primary commodities out <- out[!is.na(Value),] setnames(out,"measuredItemSuaFbs","measuredItemFbsSua") stats = SaveData(domain = "suafbs", dataset = "sua_unbalanced", data = out, waitTimeout = 2000000) paste0(stats$inserted, " observations written, ", stats$ignored, " weren't updated, ", stats$discarded, " had problems.") ################################################################ ##### send Email with notification of correct execution ##### ################################################################ ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "PullDataToSua_FBS2018 plug-in has correctly run" body = "The plug-in has saved the SUAs in your session" sendmailR::sendmail(from = from, to = to, subject = subject, msg = body) paste0("Email sent to ", swsContext.userEmail) <file_sep>/R/validateTreeShares.R ##' @title Validate shares of Commodity Trees ##' ##' This function perform Flag Validation for the commodity Tree ##' Validation. ##' The possible flags are (decided with Data Team): ##' ##' Extraction Rates: ##' (T,-) = validated up do 2013 - protected ##' (E,t) = copied from 2014 onwards - not protected but that do not change during standardization process ##' (E,f) = manually changed by the user - protected ##' ##' Shares: ##' (E,-) = coming from old methodology - NOT protected. These values willbe overwritten ##' at any run of the module, except the values of oils, which are kept, unless manually changed ##' (E,f) = manually changed by the user - protected ##' (I,i) = calculated by the module - not protected ##' ##' @param tree the commodity tree to check ##' ##' @return a list of two elements: ##' messageSH, is a message with the information of validity of flags and ##' invalidSH is a data.table which contains invalid Flags or invalid Values or is empty, if everything is valid ##' ##' @export ##' validateTreeShares = function(tree = NULL){ ## Data Quality Checks if(!exists("swsContext.datasets")){ stop("No swsContext.datasets object defined. Thus, you probably ", "won't be able to read from the SWS and so this function won't ", "work.") } # Checks for data stopifnot(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod") %in% colnames(tree)) if("5423"%in%tree[,measuredElementSuaFbs]){ stop("Elements have to be expressed in names: extractionRate, share") } # 5423 = Extraction Rate [hg/t] # 5431 = Share of utilization [%] tree=tree[,mget(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"))] ##create column for check ##(this column will be deleted) tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] ############################################################## #################### CHECK FLAG VALIDITY #################### ############################################################## validSHflags=c("(E,-)","(E,f)","(I,i)") # if There is some invalid Flag Combination OR any value outside Ranges if(any(!(tree[measuredElementSuaFbs=="share",unique(checkFlags)]%in%validSHflags))| any(tree[measuredElementSuaFbs=="share",unique(Value)]<0)| any(tree[measuredElementSuaFbs=="share",unique(Value)]>1)){ # check if Flags are invalid if(any(!(tree[measuredElementSuaFbs=="share",unique(checkFlags)]%in%validSHflags))){ # if ALSO Values are invalid if(any(tree[measuredElementSuaFbs=="share",unique(Value)]<0)| any(tree[measuredElementSuaFbs=="share",unique(Value)]>1)){ # select invalid Flags rows invalidSHf=tree[measuredElementSuaFbs=="share"&(!checkFlags%in%validSHflags)] # select also invalid values invalidSHv=tree[measuredElementSuaFbs=="share"&(Value>1|Value<0)] invalidSH=rbind(invalidSHf,invalidSHv) invalidSH[,checkFlags:=NULL] messageSH = "Invalid Flags and Figures" }else{ # if ONLY Flags are invalid invalidSH=tree[measuredElementSuaFbs=="share"&(!checkFlags%in%validSHflags)] # then the file will contain only Flags invalidSH[,checkFlags:=NULL] messageSH = "Invalid Flags and Figures" } }else{ # if ONLY VALUES are INVALID if(any(tree[measuredElementSuaFbs=="share",unique(Value)]<0)| any(tree[measuredElementSuaFbs=="share",unique(Value)]>1)){ invalidSH=tree[measuredElementSuaFbs=="share"&(Value>1|Value<0)] invalidSH[,checkFlags:=NULL] messageSH = "Invalid Flags and Figures" } } }else{ # the following Tree in empy invalidSH = tree[measuredElementSuaFbs=="share"&(Value>1|Value<0)] messageSH = "Shares Valid for the selected Tree" } return(list(messageSH=messageSH,invalidSH=invalidSH)) } <file_sep>/modules/outlierImputation/imputeLosses.R ##' # Pull data from different domains to sua ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to identify outliers in feed, seed and loss figures at sua unbalanced level ##' ##' ##' **Inputs:** ##' ##' * sua unbalanced ##' ##' **Flag assignment:** ##' ##' I e ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) #library(faoswsStandardization) library(faoswsFlag) # oldProductionCode = c("51","11","21","131") ## 51: prod, other for animals # foodCode = "5141" # importCode = "5610" # exportCode = "5910" # oldFeedCode = "101" # oldSeedCode = "111" # # #oldLossCode = "121" # lossCode = "5016" # industrialCode = "5165" # touristCode = "100" # suaTouristCode = "5164" # # Convert tourism units to tonnes # # touristConversionFactor = -1/1000 # touristConversionFactor = 1 # # warning("Stocks is change in stocks, not absolute! This needs to be changed") # stocksCode = c("5071","5113") # ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/outlierImputation/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } startYear = as.numeric(swsContext.computationParams$startYear) #startYear = as.numeric(2013) endYear = as.numeric(swsContext.computationParams$endYear) geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] top48FBSCountries = c(4,24,50,68,104,120,140,144,148,1248,170,178,218,320, 324,332,356,360,368,384,404,116,408,450,454,484,508, 524,562,566,586,604,608,716,646,686,762,834,764,800, 854,704,231,887,894,760,862,860) top48FBSCountries<-as.character(top48FBSCountries) selectedCountries = setdiff(geoKeys,top48FBSCountries) #229 # ##Select the countries based on the user input parameter # selectedGEOCode = # switch(geoM49, # "session" = sessionCountries, # "all" = selectedCountries) selectedGEOCode = sessionCountries message("Pulling SUA Unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredElementSuaFbs") eleKeys = eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = c("5510","5610","5071","5023","5910","5016","5165","5520","5525","5164","5166","5141","664","5113")) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(2010:endYear)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) protectedFlags<-ReadDatatable(table = "valid_flags") keys = c("flagObservationStatus", "flagMethod") data = GetData(key,omitna = F, normalized=F) data=normalise(data, areaVar = "geographicAreaM49", itemVar = "measuredItemFbsSua", elementVar = "measuredElementSuaFbs", yearVar = "timePointYears", flagObsVar = "flagObservationStatus", flagMethodVar = "flagMethod", valueVar = "Value", removeNonExistingRecords = F) # loss=subset(data,measuredElementSuaFbs == "5016" & flagObservationStatus=="E" & flagMethod=="e") commDef=ReadDatatable("fbs_commodity_definitions") # primaryProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X" | primary_commodity=="X"]] primary=commDef$cpc[commDef[,primary_commodity=="X"]] ProxyPrimary=commDef$cpc[commDef[,proxy_primary=="X"]] food=commDef$cpc[commDef[,food_item=="X"]] # # lossNonPrimary=subset(loss,!(measuredItemFbsSua %in% primaryProxyPrimary)) # # write.csv(lossNonPrimary,"lossNonPrimary.csv",row.names = F) data=nameData("sua_fbs","sua_unbalanced",data) data$Value[is.na(data$Value)]<-0 #lossData=subset(data,measuredElementSuaFbs == "5016") sua_unb<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(Meanold=mean(Value[timePointYears<2014],na.rm=T)) sua_unb$Meanold[is.na(sua_unb$Meanold)]<-0 sua_unb$Value[is.na(sua_unb$Value)]<-0 #sua_unb <- merge(sua_unb, protectedFlags, by = keys) ## sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(prod=sum(Value[measuredElementSuaFbs==5510])) sua_unb$prod[is.na(sua_unb$prod)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(imp=sum(Value[measuredElementSuaFbs==5610])) sua_unb$imp[is.na(sua_unb$imp)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(exp=sum(Value[measuredElementSuaFbs==5910])) sua_unb$exp[is.na(sua_unb$exp)]<-0 sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp-exp) sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio=Value/supply) sua_unb<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) ## loss careful supply definition changes sua_unb2<- sua_unb %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio=Value/supply) sua_unb2<- sua_unb2 %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio[timePointYears<2014 & timePointYears>2010],na.rm=T)) loss<-sua_unb2 %>% filter(measuredElementSuaFbs==5016) loss<-loss %>% dplyr::mutate(outl=(abs(ratio-mean_ratio)>=0.05) | (ratio==0 & mean_ratio>0)) loss$flagObservationStatus[is.na(loss$flagObservationStatus)]<-"I" loss$flagMethod[is.na(loss$flagMethod)]<-"e" outl_loss<-loss %>% filter((outl==T & timePointYears>2013 & (!((flagObservationStatus=="" & flagMethod=="q")|(flagObservationStatus=="T" & flagMethod=="p") |(flagObservationStatus=="" & flagMethod=="p")|(flagObservationStatus=="E" & flagMethod=="f"))))) impute_loss<-outl_loss %>% filter(supply>=0 & mean_ratio>0 & mean_ratio<1 & measuredItemFbsSua %in% food & measuredItemFbsSua %in% primaryProxyPrimary) impute_loss<-impute_loss %>% dplyr::mutate(impute=supply*mean_ratio) impute_loss<-impute_loss %>% dplyr::mutate(diff=Value-impute) impute_loss=setnames(impute_loss,"Value","pippo") impute_loss=setnames(impute_loss,"impute","Value") impute_loss=impute_loss[,colnames(data)] impute_loss=setDT(impute_loss) impute_loss[,flagObservationStatus:="E"] impute_loss[,flagMethod:="e"] ################################################################ ##### save data ##### ################################################################ out<-as.data.table(impute_loss) if (nrow(out) > 0) { stats = SaveData(domain = "suafbs", dataset = "sua_unbalanced", data = out, waitTimeout = 2000000) paste0(stats$inserted, " observations written, ", stats$ignored, " weren't updated, ", stats$discarded, " had problems.") ################################################################ ##### send Email with notification of correct execution ##### ################################################################ ## Initiate email from = "<EMAIL>" to = swsContext.userEmail subject = "Impute Losses plug-in has correctly run" body = "The plug-in has saved the imputed losses in your session" sendmailR::sendmail(from, to, subject , body) paste0("Email sent to ", swsContext.userEmail) } else { print("No loss figures were imputed.") } <file_sep>/modules/lossData_deletion/main.R # Retain only official loss (flagobservationStatus "" and "T") data for year 2014 in agriculture produciton domain. ## load the libraries library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsFlag) ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) SETT <- ReadSettings("modules/lossData_deletion/sws.yml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } message("Pulling Loss Data from agriculture domain in QA") #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleDim <- Dimension(name = "measuredElement", keys = c("5016")) #Define item dimension itemKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", "measuredItemCPC") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemCPC", keys = itemKeys) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = geoKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(2014:2016)) #Define the key to pull SUA data key = DatasetKey(domain = "agriculture", dataset = "aproduction", dimensions = list( geographicAreaM49 = geoDim, measuredElement = eleDim, measuredItemCPC = itemDim, timePointYears = timeDim )) loss_data <- GetData(key) data_to_delete <- loss_data[!flagObservationStatus %in% c("","T")] data_to_delete[, Value := NA_real_] data_to_delete[, flagObservationStatus := NA_character_] data_to_delete[, flagMethod := NA_character_] # Save final data to SWS cat("Save the final data...\n") stats = SaveData(domain = "agriculture", dataset = "aproduction", data = setDT(data_to_delete), waitTimeout = 1800) paste0("Only Loss Official Data have been retained for 2014") <file_sep>/R/validateTree.R ##' @title Validate ExtractionRates of Commodity Trees ##' ##' @description This function perform Flag Validation for the commodity Tree ##' Validation. ##' The possible flags are (decided with Data Team): ##' ##' Extraction Rates: ##' (T,-) = validated up do 2013 - protected ##' (E,t) = copied from 2014 onwards - not protected but that do not change during standardization process ##' (E,f) = manually changed by the user - protected ##' ##' Shares: ##' (E,-) = coming from old methodology - NOT protected. These values willbe overwritten ##' at any run of the module, except the values of oils, which are kept, unless manually changed ##' (E,f) = manually changed by the user - protected ##' (I,i) = calculated by the module - not protected ##' ##' @param tree the commodity tree to check ##' ##' @param min.er the lower limit of the range of acceptable values for Extraction Rates. ##' default to 0 ##' ##' @param max.er the upper limit of the range of acceptable values for Extraction Rates. ##' default to 7 ##' ##' @param validateShares if to check also shares flags and figures or only Extraction Rates. ##' Default set to TRUE ##' ##' @return A message with indication of validation complete or a file with values to correct ##' an email if on the system. ##' ##' @export ##' validateTree = function(tree= NULL, min.er = 0, max.er = 10, validateShares = TRUE){ ## Data Quality Checks if(!exists("swsContext.datasets")){ stop("No swsContext.datasets object defined. Thus, you probably ", "won't be able to read from the SWS and so this function won't ", "work.") } # Checks for data stopifnot(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod") %in% colnames(tree)) if("5423"%in%tree[,measuredElementSuaFbs]){ stop("Elements have to be expressed in names: extractionRate, share") } # 5423 = Extraction Rate [hg/t] # 5431 = Share of utilization [%] tree=tree[,mget(c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"))] ##create column for check ##(this column will be deleted) tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] ############################################################## #################### CHECK FLAG VALIDITY #################### ############################################################## vER=validateTreeExtractionRates(tree = tree, min.er = min.er, max.er = max.er) messageER=vER$messageER invalidER=vER$invalidER if(validateShares){ vSH=validateTreeShares(tree = tree) messageSH=vER$messageSH invalidSH=vER$invalidSH invalidTree=rbind(invalidER,invalidSH) messageTree=paste(messageER,messageSH,sep='\n') }else{ invalidTree=invalidER messageTree=messageER } if(dim(invalidTree)[1]>0){ if(!CheckDebug()){ # Create the body of the message FILETYPE = ".csv" CONFIG <- faosws::GetDatasetConfig(swsContext.datasets[[1]]@domain, swsContext.datasets[[1]]@dataset) sessionid <- ifelse(length(swsContext.datasets[[1]]@sessionId), swsContext.datasets[[1]]@sessionId, "core") basename <- sprintf("%s_%s", "invalidTreeRows", sessionid) basedir <- tempfile() dir.create(basedir) destfile <- file.path(basedir, paste0(basename, FILETYPE)) # create the csv in a temporary foldes write.csv(invalidTree, destfile, row.names = FALSE) # define on exit strategy on.exit(file.remove(destfile)) zipfile <- paste0(destfile, ".zip") withCallingHandlers(zip(zipfile, destfile, flags = "-j9X"), warning = function(w){ if(grepl("system call failed", w$message)){ stop("The system ran out of memory trying to zip up your data. Consider splitting your request into chunks") } }) on.exit(file.remove(zipfile), add = TRUE) body = paste("Standardization stopped because of:", messageTree, " ", paste0("check Share = ",validateShares), " ", "Look attached file for details", " ", "The file can be modified and uploaded in the Commodity Tree", " ", "=================================================", "Valid Flags for Commodity Tree are the following", " ", "Extraction rates:", "(T,-) = validated up do 2013 - protected", "(E,t) = copied from 2014 onwards - not protected but that do not change during standardization process", "(E,f) = manually changed by the user - protected", " ", "Shares:", "(E,-) = coming from old methodology - NOT protected. These values willbe overwritten", "any run of the module, except the values of oils, which are kept, unless manually changed", "(E,f) = manually changed by the user - protected", "(I,i) = calculated by the module - not protected", " ", "=================================================", paste0("Valid Figures for Extraction Rates are in the range: ",min.er," to ", max.er) ,sep='\n') sendmailR::sendmail(from = "<EMAIL>", to = swsContext.userEmail, subject = sprintf("Standardization stopped for invalid Flags and/or Figures"), msg = list(strsplit(body,"\n")[[1]], sendmailR::mime_part(destfile, name = paste0(basename, FILETYPE) ) ) ) stop("Process Stopped") paste0("Email sent to ", swsContext.userEmail) }else{ if(file.exists(paste0("debugFile/Batch_",batchnumber,"/B",batchnumber,"__0_invalidTreeRows.csv"))){ file.remove(paste0("debugFile/Batch_",batchnumber,"/B",batchnumber,"__0_invalidTreeRows.csv")) } dir.create(paste0(PARAMS$debugFolder,"/Batch_",batchnumber), showWarnings = FALSE,recursive=TRUE) write.csv(invalidTree, paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"__0_invalidTreeRows.csv"), row.names = FALSE) return(paste0("Process Stopped for Invalid rows in Commodity Tree. Csv file saved in: ", paste0(PARAMS$debugFolder,"/Batch_",batchnumber,"/B",batchnumber,"__0_invalidTreeRows.csv"))) } } # else{ # End of case for which flags and/or figures are invalid # if(!CheckDebug()){ # body = paste("The Commodity Tree is valid", # " ", # "If no check has been performed on Shares, be aware that shares might be invalid", # sep='\n') # sendmailR::sendmail(from = "<EMAIL>", # to = swsContext.userEmail, # subject = sprintf("tree successfully downloaded and Checked"), # msg = strsplit(body,"\n")[[1]]) # # } # message("Commodity Tree Extraction Rates are valid") # } } <file_sep>/R/findProcessingLevel.R ##' Find Processing Level ##' ##' The function finds the processing level of the item in relation to the rest ##' of the commodity items. The processing level is zero for all nodes which ##' have no inputs (i.e. they can be processed in the first round). A node with ##' inputs has it's processing level defined as 1 greater than the max ##' processing level of all of it's input nodes. Thus, nodes at level 0 are ##' processed first, as their processing doesn't depend on any other commodites. ##' Then, nodes at processing level 1 are processed because all their inputs ##' (level 0 nodes) have been computed. All nodes at a fixed processing level ##' can thus be computed in one step. ##' ##' @param edgeData The edge data, typically from the function buildEdges ##' @param from The column name of edgeData corresponding to the from node. ##' @param to The column name of edgeData corresponding to the target node. ##' @param plot Logical, indicates of the graph should be plotted. ##' @param aupusParam A list of running parameters to be used in pulling the ##' data. Typically, this is generated from getAupusParameter (see that ##' function for a description of the required elements). ##' @param errorOnLoop Logical. Should the function throw an error if a loop is ##' detected in the edgeData? If such a loop is detected, a plot is generated ##' to aid the user in finding this loop. ##' ##' @return A data.table providing the processing level for each of the items. ##' ##' @import igraph ##' ##' @export ##' findProcessingLevel = function(edgeData, from, to, plot = FALSE, aupusParam = list(itemVar = "temp"), errorOnLoop = TRUE){ e = edgeData[, c(from, to), with = FALSE] v = unique(unlist(edgeData[, c(from, to), with = FALSE])) processingGraph = igraph::graph.data.frame(d = e, vertices = v, directed = TRUE) if(plot == TRUE) plot(processingGraph, vertex.size = 6, edge.arrow.size = 0.5) root = names(which(igraph::degree(processingGraph, mode = "in") == 0 & igraph::degree(processingGraph, mode = "out") > 0)) processingLevel = igraph::shortest.paths(processingGraph, v = igraph::V(processingGraph), to = igraph::V(processingGraph)[c(root)], mode = "in") ## Take the finite maximum level from processing level finalLevels = apply(processingLevel, 1, FUN = function(x) max(x[is.finite(x)], na.rm = TRUE)) finalLevels.dt = data.table(names(finalLevels), finalLevels) setnames(finalLevels.dt, c(aupusParam$itemVar, "processingLevel")) if(errorOnLoop && finalLevels.dt[, min(processingLevel) == -Inf]){ loopNodes = finalLevels.dt[processingLevel == -Inf, get(aupusParam$itemVar)] graph = graph.data.frame(edges[get(from) %in% loopNodes | get(to) %in% loopNodes, ]) plot(graph) stop("Loops detected in commodity tree! Check vertices:\n", paste(loopNodes, collapse = "\n")) } return(finalLevels.dt[order(processingLevel), ]) } <file_sep>/modules/FullstandardizationAndBalancing/main.R #sapply(dir("R", full.names = TRUE), source) options(scipen=999) commence<-Sys.time() ## load the library library(faosws) library(faoswsUtil) library(faoswsBalancing) library(faoswsStandardization) library(faoswsFlag) message("libraries loaded") library(data.table) library(igraph) library(stringr) library(dplyr) # library(dtplyr) library(MASS) library(lattice) library(reshape2) library(sendmailR) library(tidyr) if(packageVersion("faoswsStandardization") < package_version('0.1.0')){ stop("faoswsStandardization is out of date") } ## set up for the test environment and parameters R_SWS_SHARE_PATH = Sys.getenv("R_SWS_SHARE_PATH") if (CheckDebug()) { library(faoswsModules) message("Not on server, so setting up environment...") # Read settings file sws.yml in working directory. See # sws.yml.example for more information PARAMS <- ReadSettings("modules/fullStandardizationAndBalancing/sws.yml") message("Connecting to server: ", PARAMS[["current"]]) R_SWS_SHARE_PATH = PARAMS[["share"]] apiDirectory = "./R" ## Get SWS Parameters SetClientFiles(dir = PARAMS[["certdir"]]) GetTestEnvironment( baseUrl = PARAMS[["server"]], token = PARAMS[["token"]] ) batchnumber = 1 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT } else { batchnumber = 000 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SET IT message("Running on server, no need to call GetTestEnvironment...") } #User name is what's after the slash SWS_USER = regmatches(swsContext.username, regexpr("(?<=/).+$", swsContext.username, perl = TRUE)) # instead of replace the existing # (for example save example files for different batches) # put the name in the .yml file # default is NULL if(CheckDebug()){ SUB_FOLDER = paste0(PARAMS[["subShare"]],batchnumber) } message("Getting parameters/datasets...") COUNTRY <- as.character(swsContext.datasets[[1]]@dimensions$geographicAreaM49@keys) COUNTRY_NAME <- nameData( "suafbs", "sua_unbalanced", data.table(geographicAreaM49 = COUNTRY))$geographicAreaM49_description # start and end year for standardization come from user parameters startYear = swsContext.computationParams$startYear endYear = swsContext.computationParams$endYear geoM49 = swsContext.computationParams$geom49 stopifnot(startYear <= endYear) yearVals = as.character(startYear:endYear) outlierMail = swsContext.computationParams$checks ## Get data configuration and session sessionKey_fbsBal = swsContext.datasets[[1]] #sessionKey_suaUnb = swsContext.datasets[[2]] sessionKey_suabal = swsContext.datasets[[2]] sessionKey_fbsStand = swsContext.datasets[[3]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey_fbsBal) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] # Select the countries based on the user input parameter selectedGEOCode = switch(geoM49, "session" = sessionCountries, "all" = geoKeys) areaKeys = selectedGEOCode ############################################################## ############ DOWNLOAD AND VALIDATE TREE ###################### ############################################################## ptm <- proc.time() #tree=getCommodityTreeNewMethod(areaKeys,yearVals) message("Downloading tree...") tree=getCommodityTreeNewMethod(areaKeys,as.character(2000:2018)) message((proc.time() - ptm)[3]) # Exception: high share conmfirmed by official data tree_exceptions <- tree[geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01"] if (nrow(tree_exceptions) > 0) { tree <- tree[!(geographicAreaM49 == "392" & measuredItemParentCPC == "0141" & measuredItemChildCPC == "23995.01")] } validateTree(tree) if (nrow(tree_exceptions) > 0) { tree <- rbind(tree, tree_exceptions) rm(tree_exceptions) } # NA ExtractionRates are recorded in the sws dataset as 0 # for the standardization, we nee them to be treated as NA # therefore here we are re-changing it tree[Value==0,Value:=NA] #fILL EXTRACTION RATE--------------------- expanded_tree <- merge( data.table( expand.grid( geographicAreaM49 = unique(tree$geographicAreaM49), timePointYears = sort(unique(tree$timePointYears)) )), unique(tree[, .(geographicAreaM49, measuredElementSuaFbs, measuredItemParentCPC, measuredItemChildCPC)]), by = "geographicAreaM49", all = TRUE, allow.cartesian = TRUE ) tree <- tree[expanded_tree, on = colnames(expanded_tree)] # flags for carry forward/backward tree[is.na(Value), c("flagObservationStatus", "flagMethod") := list("E", "t")] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = -Inf ] tree <- tree[!is.na(Value)][ tree, on = c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), roll = Inf ] # keep orig flags tree[, flagObservationStatus := i.i.flagObservationStatus] tree[, flagMethod := i.i.flagMethod] tree[, names(tree)[grep("^i\\.", names(tree))] := NULL] # saveRDS( # tree[ # !is.na(Value) & measuredElementSuaFbs == "extractionRate", # -grepl("measuredElementSuaFbs", names(tree)), # with = FALSE # ], # file.path(R_SWS_SHARE_PATH, "FBS_validation", COUNTRY, "tree.rds") # ) #END FILL EXTRACTION RATE------------- ############GLOBAL EXTRACTION RATE ########################### #globalExtr=read.csv(file.path(R_SWS_SHARE_PATH, "standardization", "Global_Extraction_Rates.csv")) ################################################################## ##########################FUNCTIONS############################### ################################################################# send_mail <- function(from = NA, to = NA, subject = NA, body = NA, remove = FALSE) { if (missing(from)) from <- '<EMAIL>' if (missing(to)) { if (exists('swsContext.userEmail')) { to <- swsContext.userEmail } } if (is.null(to)) { stop('No valid email in `to` parameter.') } if (missing(subject)) stop('Missing `subject`.') if (missing(body)) stop('Missing `body`.') if (length(body) > 1) { body <- sapply( body, function(x) { if (file.exists(x)) { # https://en.wikipedia.org/wiki/Media_type file_type <- switch( tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), txt = 'text/plain', csv = 'text/csv', png = 'image/png', jpeg = 'image/jpeg', jpg = 'image/jpeg', gif = 'image/gif', xls = 'application/vnd.ms-excel', xlsx = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', doc = 'application/msword', docx = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf = 'application/pdf', zip = 'application/zip', # https://stackoverflow.com/questions/24725593/mime-type-for-serialized-r-objects rds = 'application/octet-stream' ) if (is.null(file_type)) { stop(paste(tolower(sub('.*\\.([^.]+)$', '\\1', basename(x))), 'is not a supported file type.')) } else { res <- sendmailR:::.file_attachment(x, basename(x), type = file_type) if (remove == TRUE) { unlink(x) } return(res) } } else { return(x) } } ) } else if (!is.character(body)) { stop('`body` should be either a string or a list.') } sendmailR::sendmail(from, to, subject, as.list(body)) } calculateImbalance <- function(data, supply_add = c("production", "imports"), supply_subtract = c("exports", "stockChange"), supply_all = union(supply_add, supply_subtract), item_name = "measuredItemFbsSua", bygroup = c("geographicAreaM49", "timePointYears", item_name), keep_supply = TRUE, keep_utilizations = TRUE) { stopifnot(is.data.table(data)) data[measuredElementSuaFbs %!in% c("residual","TotalCalories","TotalProteins", "TotalFats","calories","proteins","fats"), `:=`( supply = sum(Value[measuredElementSuaFbs %chin% supply_add], - Value[measuredElementSuaFbs %chin% supply_subtract], na.rm = TRUE), # All elements that are NOT supply elements utilizations = sum(Value[!(measuredElementSuaFbs %chin% supply_all)], na.rm = TRUE) ), by = bygroup ][, imbalance := supply - utilizations ] if (keep_supply == FALSE) { data[, supply := NULL] } if (keep_utilizations == FALSE) { data[, utilizations := NULL] } } RemainingToProcessedParent <- function(data) { data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] data[, only_child_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(production_of_child) & !is.na(parent_qty_processed) & production_of_child > 0, by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[ only_child_left == TRUE, processed_to_child := remaining_processed_parent * extractionRate ] data[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate, na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data[remaining_processed_parent < 0, remaining_processed_parent := 0] return(data) } RemainingProdChildToAssign <- function(data) { data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] data[, only_parent_left := sum(is.na(processed_to_child)) == 1 & is.na(processed_to_child) & !is.na(parent_qty_processed) & parent_qty_processed >= 0 ] data[only_parent_left==TRUE,processed_to_child:=ifelse(only_parent_left==TRUE,remaining_to_process_child,processed_to_child)] data[, available_processed_child := sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] data[, remaining_to_process_child := round(production_of_child - available_processed_child)] data[remaining_to_process_child < 0, remaining_to_process_child := 0] return(data) } # Replacement for merge(x, y, by = VARS, all.x = TRUE) that do not set keys # By default it behaves as dplyr::left_join(). If nomatch = 0, non-matching # rows will not be returned dt_left_join <- function(x, y, by = NA, allow.cartesian = FALSE, nomatch = NA) { if (anyNA(by)) { stop("'by' is required") } if (any(!is.data.table(x), !is.data.table(y))) { stop("'x' and 'y' should be data.tables") } res <- y[x, on = by, allow.cartesian = allow.cartesian, nomatch = nomatch] setcolorder(res, c(names(x), setdiff(names(y), names(x)))) res } standardizeTree = function(data, tree, elements, standParams,zeroWeight=c(), sugarHack = TRUE){ ## Assign parameters geoVar = standParams$geoVar yearVar = standParams$yearVar itemVar = standParams$itemVar elementPrefix = standParams$elementPrefix childVar = standParams$childVar parentVar = standParams$parentVar extractVar = standParams$extractVar shareVar = standParams$shareVar protected = standParams$protected ## Data Quality Checks stopifnot(is(data, "data.table")) stopifnot(is(tree, "data.table")) stopifnot(c(geoVar, yearVar, itemVar, paste0(elementPrefix, elements)) %in% colnames(data)) stopifnot(c(geoVar, yearVar, childVar, parentVar, extractVar, shareVar) %in% colnames(tree)) if(!all(sapply(data[, paste0(elementPrefix, c(elements)), with = FALSE], is.numeric))){ stop("Some of the elements passed are not numeric!") } if(!"target" %in% colnames(tree)){ tree[, target := "B"] } stopifnot(all(tree[, target] %in% c("B", "T", "F"))) if(!"standDev" %in% colnames(tree)){ returnStandDev = FALSE tree[, standDev := 0] } else { returnStandDev = TRUE } stopifnot(all(tree[, standDev] >= 0)) elements = paste0(elementPrefix, elements) ## Restructure the data for easier standardization standardizationData = data.table::melt.data.table( data = data, measure.vars = elements, id.vars = c(geoVar, yearVar, itemVar,protected), variable.name = "measuredElement", value.name = "Value") standardizationData[, measuredElement := gsub(elementPrefix, "", measuredElement)] ## To ensure commodities are standardized up multiple levels, we have to ## collapse the tree (otherwise if A -> B -> C in the tree, C may be ## standardized only to B and not to A, as desired). standKey = standParams$mergeKey[standParams$mergeKey != standParams$itemVar] if(dim(tree)[1]!=0){ tree = collapseEdges(edges = tree, parentName = standParams$parentVar, childName = standParams$childVar, extractionName = standParams$extractVar, keyCols = standKey) ## Merge the tree with the node data tree[, c(parentVar, childVar, yearVar, geoVar) := list(as.character(get(parentVar)), as.character(get(childVar)), as.character(get(yearVar)), as.character(get(geoVar)))] } setnames(standardizationData, itemVar, childVar) standardizationData[, c(childVar, yearVar, geoVar) := list(as.character(get(childVar)), as.character(get(yearVar)), as.character(get(geoVar)))] ## To deal with joint byproducts standardizationData = merge(standardizationData, tree, by = c(yearVar, geoVar, childVar), all.x = TRUE, allow.cartesian = TRUE) ##' If an element is not a child in the tree, then "standardize" it to ##' itself with a rate of 1 and a share of 1. standardizationData[is.na(get(parentVar)), c(parentVar, extractVar, shareVar) := list(get(childVar), 1, 1)] standardizationData[,weight:=1] standardizationData[measuredItemChildCPC %in% zeroWeight , weight:=0] ## Standardizing backwards is easy: we just take the value, divide by the ## extraction rate, and multiply by the shares. However, we don't ## standardize the production element (because production of flour is ## derived from the production of wheat already). We standardize everything ## backwards, and then edges marked as forwards (i.e. target == "F") get ## standardized down. # Extraction rates of zero will cause us to divide by zero, so we must # remove them extract0 <- standardizationData[abs(get(extractVar)) < .Machine$double.eps ^ .5] if(nrow(extract0) > 0){ # Check for tricky floating point issues, but checking if equal to 0 warning(sprintf("Extraction rates of 0 present in commodity codes: {%s} in country {%s}. Ignoring all extraction rates of 0 in backwards standardization", paste0(unique(extract0[, get(parentVar)]), collapse = ", "), unique(extract0[, get(geoVar)]))) standardizationData[abs(get(extractVar)) < .Machine$double.eps^.5, Value := NA] } output = standardizationData[, list( Value = sum( Value * weight /get(extractVar)*get(shareVar), na.rm = TRUE)), by = c(yearVar, geoVar, "measuredElement", parentVar)] forwardEdges = tree[target == "F", ] ## Reshape to put back into the same shape as the passed data setnames(output, parentVar, itemVar) output[, measuredElement := paste0(elementPrefix, measuredElement)] form = as.formula(paste(yearVar, "+", geoVar, "+", itemVar, "~ measuredElement")) output = dcast.data.table(data = output, formula = form, value.var = "Value", fun.aggregate = mean, na.rm = TRUE) return(output) } #TO DO: move this function bellow to the R folder and commit in github collapseEdges_NEW = function(edges, parentName = "parentID", childName = "childID", extractionName = "extractionRate", keyCols = c("timePointYearsSP", "geographicAreaFS"), notStandChild,weight="weight",standard_child="standard_child"){ ## Data quality checks stopifnot(is(edges, "data.table")) stopifnot(c(parentName, childName, extractionName) %in% colnames(edges)) if(max(edges[[extractionName]][edges[[extractionName]] < Inf]) > 100) stop("Extraction rates larger than 100 indicate they are probably ", "expressed in different units than on [0,1]. This will cause ", "huge problems when multiplying, and should be fixed.") #cyclic parent-child relation bring infinit loop if (COUNTRY %!in% "470"){ edges<-edges[!(get(parentName)=="21529.03" & get(childName)=="21523")] } ## Test for loops # findProcessingLevel(edgeData = edges, from = parentName, # to = childName) nonstand<-edges[get(parentName) %in% notStandChild] nonstand<-nonstand[,get(parentName)] targetNodes = setdiff(edges[[parentName]], edges[[childName]]) targetNodes=unique(c(targetNodes,nonstand)) edgesCopy = copy(edges[, c(parentName, childName, extractionName,p$shareVar,weight,standard_child,"som", keyCols), with = FALSE]) setnames(edgesCopy, c(parentName, childName, extractionName,p$shareVar,weight,standard_child,"som"), c("newParent", parentName, "extractionMult","share.parent","weight.Parent","standard_child.parent","som.parrent")) finalEdges = edges[get(parentName) %in% targetNodes, ] currEdges = edges[!get(parentName) %in% targetNodes, ] while(nrow(currEdges) > 0){ currEdges = merge(currEdges, edgesCopy, by = c(parentName, keyCols), all.x = TRUE, allow.cartesian = TRUE) ## Update edges table with new parents/extraction rates. For edges that ## didn't get changed, we keep the old parent name and extraction rate. currEdges[, c(p$shareVar) := get(p$shareVar) *(share.parent/sum(share.parent,na.rm = TRUE)), by=c(p$geoVar,p$yearVar,childName,parentName) ] currEdges[, c(parentName) := ifelse(is.na(newParent), get(parentName), newParent)] currEdges[, c(extractionName) := get(extractionName) * ifelse(is.na(extractionMult), 1, extractionMult)] # currEdges[,c(weight):=ifelse(!is.na(weight.Parent),weight.Parent,get(weight))] currEdges[,c(weight):=ifelse(weight.Parent==0,weight.Parent,weight)] currEdges[,c(standard_child):=ifelse(standard_child.parent==TRUE & standard_child==TRUE, TRUE,FALSE)] currEdges[,c(weight):=ifelse(som.parrent==1 & standard_child.parent==FALSE,0,weight)] currEdges[, c("newParent", "extractionMult","share.parent","weight.Parent","standard_child.parent","som.parrent") := NULL] finalEdges = rbind(finalEdges, currEdges[get(parentName) %in% targetNodes, ]) currEdges = currEdges[!get(parentName) %in% targetNodes, ] } finalEdges = unique(finalEdges,by=colnames(finalEdges)) # finalEdges[,standard_child:=ifelse(get(childName) %in% notStandChild,FALSE,TRUE)] finalEdges = unique(finalEdges,by=colnames(finalEdges)) return(finalEdges) } computeFbsAggregate = function(data, fbsTree, standParams){ ## Data Quality Checks stopifnot(standParams$itemVar %in% colnames(data)) stopifnot(standParams$itemVar %in% colnames(fbsTree)) stopifnot(paste0("fbsID", 1:4) %in% colnames(fbsTree)) fbsTree[measuredItemSuaFbs=="23670.01",fbsID4:="2542"] fbsTree[measuredItemSuaFbs=="23670.01",fbsID2:="2903"] if(data[,unique(geographicAreaM49)]%in%c("72")){ fbsTree[measuredItemSuaFbs=="23670.01",fbsID4:="2543"] fbsTree[measuredItemSuaFbs=="23670.01",fbsID2:="2903"] } data = merge(data, fbsTree, by = standParams$itemVar) out = list() out[[1]] = data[,list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID4")] out[[2]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID3")] out[[3]] = data[, list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID2")] out[[4]] = data[get(standParams$elementVar) %in% c(standParams$calories, standParams$proteins, standParams$fats, "TotalCalories", "TotalProteins", "TotalFats"), list(Value = sum(Value, na.rm = TRUE)), by = c(standParams$elementVar, standParams$yearVar, standParams$geoVar, "fbsID1")] return(out) } getShareUpDownTree = function(geographicAreaM49 = NULL, timePointYears = NULL){ treeelemKeys = c("5431") treeitemPKeys = GetCodeList(domain = "suafbs", dataset = "up_down_share", "measuredItemParentCPC_tree") treeitemPKeys = treeitemPKeys[, code] treeitemCKeys = GetCodeList(domain = "suafbs", dataset = "up_down_share", "measuredItemChildCPC_tree") treeitemCKeys = treeitemCKeys[, code] treekey = faosws::DatasetKey(domain = "suafbs", dataset = "up_down_share", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = geographicAreaM49), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = treeelemKeys), measuredItemParentCPC = Dimension(name = "measuredItemParentCPC_tree", keys = treeitemPKeys), measuredItemChildCPC = Dimension(name = "measuredItemChildCPC_tree", keys = treeitemCKeys), timePointYears = Dimension(name = "timePointYears", keys = timePointYears) )) ## Extract the specific tree ShareUpDownTree = faosws::GetData(treekey,omitna = FALSE) ShareUpDownTree[measuredElementSuaFbs=="5431",measuredElementSuaFbs:="shareUpDown"] message("ShareUpDownTree correctly downloaded") setnames(ShareUpDownTree,c("measuredItemParentCPC_tree","measuredItemChildCPC_tree"), c("measuredItemParentCPC","measuredItemChildCPC")) return(ShareUpDownTree) } #Function that allow to compute the list of child commodities that #should not be standardized (because they are not in the same fbstree than their parent) NonStandardizedChidren<-function(fbsTree,tree,standParams){ ## Data Quality Checks stopifnot(standParams$parentVar %in% colnames(tree)) stopifnot(standParams$childVar %in% colnames(tree)) stopifnot(standParams$itemVar %in% colnames(fbsTree)) stopifnot(paste0("fbsID", 1:4) %in% colnames(fbsTree)) fbstreebis<-copy(fbsTree) #FSB group of parents setnames(fbstreebis,"measuredItemSuaFbs",standParams$parentVar) treeFBSmerge<-merge( tree, fbstreebis, by=c(standParams$parentVar), allow.cartesian = TRUE, all.x = TRUE ) setnames(treeFBSmerge,"fbsID4","fbsID4_parent") treeFBSmerge[,`:=`(fbsID3=NULL,fbsID2=NULL,fbsID1=NULL)] #FSB group of child commdities setnames(fbstreebis,standParams$parentVar,standParams$childVar) treeFBSmerge<-merge( treeFBSmerge, fbstreebis, by=c(standParams$childVar), allow.cartesian = TRUE, all.x = TRUE ) setnames(treeFBSmerge,"fbsID4","fbsID4_child") treeFBSmerge[,`:=`(fbsID3=NULL,fbsID2=NULL,fbsID1=NULL)] #this variable takes TRUE if the child should be standardized ( have the same #FBS tree than the parent) treeFBSmerge[,standard_child:=ifelse(fbsID4_parent==fbsID4_child,TRUE,FALSE)] #tree[is.na(standard_child),standard_child:=FALSE] treeFBSmerge<-#unique( treeFBSmerge[,list(geographicAreaM49,timePointYears,measuredItemParentCPC,measuredItemChildCPC,standard_child)] #by=c("measuredItemChildCPC","standard_child") #) treefbs<-unique(treeFBSmerge, by=c(colnames(treeFBSmerge))) #there some cases where the multiparent child commodity have 2 parents and is in the FBS #group than only 1 parent. In that case it is comnsidered as standardized (even if for the other parent it will be false) #it is the case starch of potaote that has 2 parent: potaote ans sweet potatoe but is the same FBS group than potatoe # # treeFBSmerge[,som:=sum(standard_child,na.rm = TRUE), # by=c("measuredItemChildCPC")] # # #keep only child commodities that should not be standardized # treeFBSmerge<-treeFBSmerge[som==0 & !is.na(standard_child)] # treeFBSmerge[,som:=NULL] # output<-treeFBSmerge #[,get(p$childVar)] return(treeFBSmerge) } # rollavg() is a rolling average function that uses computed averages # to generate new values if there are missing values (and FOCB/LOCF). # I.e.: # vec <- c(NA, 2, 3, 2.5, 4, 3, NA, NA, NA) # #> RcppRoll::roll_mean(myvec, 3, fill = 'extend', align = 'right') #[1] NA NA NA 2.500000 3.166667 3.166667 NA NA NA # #> rollavg(myvec) #[1] 2.000000 2.000000 3.000000 2.500000 4.000000 3.000000 3.166667 3.388889 3.185185 # rollavg <- function(x, order = 3) { # # order should be > 2 # stopifnot(order >= 3) # # non_missing <- sum(!is.na(x)) # # # For cases that have just two non-missing observations # order <- ifelse(order > 2 & non_missing == 2, 2, order) # # if (non_missing == 1) { # x[is.na(x)] <- na.omit(x)[1] # } else if (non_missing >= order) { # n <- 1 # while(any(is.na(x)) & n <= 10) { # 10 is max tries # movav <- suppressWarnings(RcppRoll::roll_mean(x, order, fill = 'extend', align = 'right')) # movav <- data.table::shift(movav) # x[is.na(x)] <- movav[is.na(x)] # n <- n + 1 # } # # x <- zoo::na.fill(x, 'extend') # } # # return(x) # } `%!in%` = Negate(`%in%`) ###########END FUNCTION-------------------------------------------- #QUick way to have the exact shareDownUp #LoadShareUpDowm shareUpDownTree=getShareUpDownTree(areaKeys,as.character(2000:2018)) shareUpDownTree<-shareUpDownTree[!is.na(Value)] shareUpDownTree[,shareUpDown:=Value] shareUpDownTree[,Value:=NULL] shareUpDownTree[,flagObservationStatus:=NULL] shareUpDownTree[,flagMethod:=NULL] ############################################################## ################### MARK OILS COMMODITY ###################### ############################################################## oilFatsCPC=c("2161", "2162", "21631.01", "21641.01", "21641.02", "2168", "21691.14", "2165", "34120", "21932.02", "2166", "21691.07", "2167", "21673", "21691.01", "21691.02", "21691.03", "21691.04", "21691.05", "21691.06", "21631.02", "21691.08", "21691.09", "21691.10", "21691.11", "21691.12", "21691.13", "21691.90", "23620", "21700.01", "21700.02", "21693.02", "34550", "F1275", "21512", "21512.01", "21513", "21514", "F0994", "21515", "21511.01", "21511.02", "21521", "21511.03", "21522", "21519.02", "21519.03", "21529.03", "21529.02", "21932.01", "21523", "F1243", "F0666") tree[(measuredItemParentCPC%in%oilFatsCPC|measuredItemChildCPC%in%oilFatsCPC),oil:=TRUE] ############################################################## ################ CLEAN NOT OFFICIAL SHARES ################### ################ & SHARES EXCEPT OILS ################### ############################################################## ## (E,f) have to be kept ## any other has to ve cleaned except the oils tree[,checkFlags:=paste0("(",flagObservationStatus,",",flagMethod,")")] tree[measuredElementSuaFbs=="share"&(checkFlags=="(E,f)"|oil==TRUE),keep:=TRUE] tree[measuredElementSuaFbs=="share"&is.na(keep),Value:=NA] tree<-tree[timePointYears %in% yearVals,] tree[,checkFlags:=NULL] tree[,oil:=NULL] tree[,keep:=NULL] ############################################################## ############ Set parameters for specific dataset ############# ############################################################## params = defaultStandardizationParameters() params$itemVar = "measuredItemSuaFbs" params$mergeKey[params$mergeKey == "measuredItemCPC"] = "measuredItemSuaFbs" params$elementVar = "measuredElementSuaFbs" params$childVar = "measuredItemChildCPC" params$parentVar = "measuredItemParentCPC" params$productionCode = "production" params$importCode = "imports" params$exportCode = "exports" params$stockCode = "stockChange" params$foodCode = "food" params$feedCode = "feed" params$seedCode = "seed" params$wasteCode = "loss" params$industrialCode = "industrial" params$touristCode = "tourist" params$foodProcCode = "foodManufacturing" params$residualCode = "residual" params$createIntermetiateFile= "TRUE" params$protected = "Protected" params$official = "Official" params$calories = "calories" params$proteins = "proteins" params$fats = "fats" ############################################################## ######## CLEAN ALL SESSION TO BE USED IN THE PROCESS ######### ############################################################## ## CLEAN fbs_standardized message("wipe fbs_standardized session") CONFIG <- GetDatasetConfig(sessionKey_fbsStand@domain, sessionKey_fbsStand@dataset) fbs_standardized=GetData(sessionKey_fbsStand) fbs_standardized=fbs_standardized[timePointYears%in%yearVals] fbs_standardized[, Value := NA_real_] fbs_standardized[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = fbs_standardized, waitTimeout = Inf) ## CLEAN fbs_balanced message("wipe fbs_balanced session") CONFIG <- GetDatasetConfig(sessionKey_fbsBal@domain, sessionKey_fbsBal@dataset) fbs_balancedData=GetData(sessionKey_fbsBal) fbs_balancedData=fbs_balancedData[timePointYears%in%yearVals] fbs_balancedData[, Value := NA_real_] fbs_balancedData[, CONFIG$flags := NA_character_] SaveData(CONFIG$domain, CONFIG$dataset , data = fbs_balancedData, waitTimeout = Inf) ############################################################## #################### SET KEYS FOR DATA ####################### ############################################################## elemKeys=c("5510", "5610", "5071", "5023", "5910", "5016", "5165", "5520","5525","5164","5166","5141") # 5510 Production[t] # 5610 Import Quantity [t] # 5071 Stock Variation [t] # 5023 Export Quantity [t] # 5910 Loss [t] # 5016 Industrial uses [t] # 5165 Feed [t] # 5520 Seed [t] # 5525 Tourist Consumption [t] # 5164 Residual other uses [t] # 5166 Food [t] # 5141 Food Supply (/capita/day) [Kcal] #desKeys = c("664","674","684") desKeys = c("664") #TODO GENERATE FATES AND PROTEINS IN THE sua balanced # 664 Food Supply (Kcal/caput/day) [kcal] # 674 Protein Supply quantity (g/caput/day) [g] # 684 Fat supply quantity (g/caput/day) [g] itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_balanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), timePointYears = Dimension(name = "timePointYears", keys = as.character(2000:2018)))) # key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( # geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), # measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = elemKeys), # measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), # timePointYears = Dimension(name = "timePointYears", keys = yearVals))) # # keyDes = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( # geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = areaKeys), # measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = desKeys), # measuredItemFbsSua = Dimension(name = "measuredItemFbsSua", keys = itemKeys), # timePointYears = Dimension(name = "timePointYears", keys = yearVals))) ############################################################## ####################### DOWNLOAD DATA ####################### ############################################################## message("Reading SUA data...") #get sua bal Data CONFIG <- GetDatasetConfig(sessionKey_suabal@domain, sessionKey_suabal@dataset) SuabalData=GetData(sessionKey_suabal) SuabalData=SuabalData[timePointYears%in%yearVals] # SuabalData=SuabalData[geographicAreaM49 %in% c("360")] setnames(SuabalData,"measuredItemFbsSua",params$itemVar) #Sua balanced quantitise data=SuabalData[get(params$elementVar) %in% elemKeys,] data=elementCodesToNames(data,standParams = params) data[measuredElementSuaFbs=="foodmanufacturing",measuredElementSuaFbs:="foodManufacturing"] data[measuredElementSuaFbs=="stock_change",measuredElementSuaFbs:="stockChange"] #data[measuredElementSuaFbs=="stock",measuredElementSuaFbs:="stockChange"] message("delete null elements") data=data[!is.na(measuredElementSuaFbs)] data_residual<-data[measuredElementSuaFbs %!in% c("residual")] setnames(data_residual,"measuredItemSuaFbs" ,"measuredItemFbsSua") calculateImbalance(data=data_residual,keep_supply = FALSE,keep_utilizations = FALSE) data_residual[,`:=`(Value=imbalance, measuredElementSuaFbs="residual", flagObservationStatus="I", flagMethod="i", imbalance=NULL)] setnames(data_residual,"measuredItemFbsSua","measuredItemSuaFbs") data_residual<-unique(data_residual, by=colnames(data)) data<-rbind(data[measuredElementSuaFbs %!in% c("residual")],data_residual) #Sua balanced DES # dataDes<-SuabalData[get(params$elementVar) %in% desKeys] # dataDes[get(params$elementVar)=="664",params$elementVar:=params$calories] message("load SUA unbal data...") # dataSuaUn = elementCodesToNames(data = GetData(key), itemCol = "measuredItemFbsSua", # elementCol = "measuredElementSuaFbs") #########SHARE DOWNUP ---------------------------------------------- ############################nEW WAY TO GENERATE SHAREDOWN UP-------------------------------------- message("derivation of shareDownUp") p<-params ############# ShareDownUp ---------------------------------------- #this table will be used to assign to zeroweight comodities #the processed quantities of their coproduct coproduct_table <- ReadDatatable('zeroweight_coproducts') zeroWeight=ReadDatatable("zero_weight")[,item_code] stopifnot(nrow(coproduct_table) > 0) # Can't do anything if this information if missing, so remove these cases coproduct_table <- coproduct_table[!is.na(branch)] ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ### XXX removing these cases as '22242.01' appears as zero-weight XXXX ### XXX for main product = '22110.04' XXXX ### XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX coproduct_table <- coproduct_table[branch != '22242.01 + 22110.04'] coproduct_table <- coproduct_table[, .(measured_item_child_cpc, branch)] coproduct_for_sharedownup <- copy(coproduct_table) coproduct_for_sharedownup_easy <- coproduct_for_sharedownup[!grepl('\\+|or', branch)] coproduct_for_sharedownup_plus <- coproduct_for_sharedownup[grepl('\\+', branch)] coproduct_for_sharedownup_plus <- rbind( tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_plus, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *\\+ *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_plus <- unique(coproduct_for_sharedownup_plus) coproduct_for_sharedownup_or <- coproduct_for_sharedownup[grepl('or', branch)] coproduct_for_sharedownup_or <- rbind( #coproduct_table_or, tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc, branch= main1)], tidyr::separate( coproduct_for_sharedownup_or, branch, into = c('main1', 'main2'), remove = FALSE, sep = ' *or *')[, .(measured_item_child_cpc,branch = main2)] ) coproduct_for_sharedownup_or <- unique(coproduct_for_sharedownup_or) coproduct_for_sharedownup <- rbind( coproduct_for_sharedownup_easy, coproduct_for_sharedownup_plus, coproduct_for_sharedownup_or ) # tree<-tree[geographicAreaM49=="360" & timePointYears>2013] #Using the whole tree not by level ExtrRate <- tree[ !is.na(Value) & measuredElementSuaFbs == 'extractionRate' ][, .( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value ) ] # We include utilizations to identify if proceseed if the only utilization data_tree <- data[ measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange', 'foodManufacturing', 'loss', 'food', 'industrial', 'feed', 'seed') ] #subset the tree accordingly to parents and child present in the SUA data # ExtrRate <- # ExtrRate[ # measuredItemChildCPC %chin% data_tree$measuredItemSuaFbs & # measuredItemParentCPC %chin% data_tree$measuredItemSuaFbs # ] setnames(data_tree, "measuredItemSuaFbs", "measuredItemParentCPC") data_tree <- merge( data_tree, ExtrRate, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE, all.y = TRUE ) data_tree <- as.data.table(data_tree) # the availability for parent that have one child and only processed as utilization will # be entirely assigned to processed for that its unique child even for 2014 onwards data_tree[, availability := sum( Value[get(p$elementVar) %in% c(p$productionCode, p$importCode)], - Value[get(p$elementVar) %in% c(p$exportCode, "stockChange")], na.rm = TRUE ), by = c(p$geoVar, p$yearVar, p$parentVar, p$childVar) ] # used to chack if a parent has processed as utilization data_tree[, proc_Median := median( Value[measuredElementSuaFbs == "foodManufacturing" & timePointYears %in% 2000:2018], na.rm=TRUE ), by = c(p$parentVar, p$geoVar) ] # boolean variable taking TRUE if the parent has only processed as utilization data_tree[, unique_proc := proc_Median > 0 & !is.na(proc_Median) & # ... is the only utilization all(is.na(Value[!(measuredElementSuaFbs %chin% c('production', 'imports', 'exports', 'stockChange','foodManufacturing'))])), by = c(p$parentVar, p$geoVar, p$yearVar) ] sel_vars <- c("measuredItemParentCPC", "geographicAreaM49", "timePointYears", "measuredElementSuaFbs", "flagObservationStatus", "flagMethod", "Value", "measuredItemChildCPC", "extractionRate" ) data_tree<- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) # dataset to calculate the number of parent of each child and the number of children of each parent # including zeroweight commodities sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC","timePointYears") data_count <- unique(data_tree[, sel_vars, with = FALSE], by = sel_vars) #Caculate the number of parent of each child data_count[, number_of_parent := .N, by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # calculate the number of children of each parent # we exclude zeroweight to avoid doublecounting of children (processing) data_count[measuredItemChildCPC %!in% zeroWeight, number_of_children := uniqueN(measuredItemChildCPC), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree <- dt_left_join( data_tree, data_count, by = c(p$parentVar, p$childVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) # dataset containing the processed quantity of parents food_proc <- unique( data_tree[ measuredElementSuaFbs == "foodManufacturing", c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value"), with = FALSE ], by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears", "Value") ) setnames(food_proc, "Value", "parent_qty_processed") # avoid recaculation of shareDownUp from 2014 onwards # food_proc[timePointYears > 2013, parent_qty_processed := NA_real_] data_tree <- dt_left_join( data_tree, food_proc, by = c(p$parentVar, p$geoVar, p$yearVar), allow.cartesian = TRUE ) sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "extractionRate", "parent_qty_processed", "number_of_parent", "number_of_children") data_tree <- unique( data_tree[, c(sel_vars, "availability", "unique_proc"), with = FALSE], by = sel_vars ) # dataset containing the production of child commodities dataprodchild <- data[measuredElementSuaFbs %chin% c('production')] setnames(dataprodchild, "measuredItemSuaFbs", "measuredItemChildCPC") dataprodchild <- unique( dataprodchild[, c("geographicAreaM49", "measuredItemChildCPC", "timePointYears", "Value", "flagObservationStatus", "flagMethod"), with = FALSE ] ) setnames(dataprodchild, "Value", "production_of_child") # to avoid resestimation based on estimated data (processed and production of child) from 2014 onwards # dataprodchild[timePointYears > 2013, production_of_child := NA_real_] data_tree <- dt_left_join( data_tree, dataprodchild, by = c(p$geoVar, p$childVar, p$yearVar) ) # ShareDownups for zeroweights are calculated separately # to avoid double counting when agregating processed quantities of parent # dataset containing informations of zeroweight commodities data_zeroweight <- data_tree[measuredItemChildCPC %chin% zeroWeight] # import data for coproduct relation zw_coproduct <- coproduct_for_sharedownup[, .(zeroweight = measured_item_child_cpc, measuredItemChildCPC = branch) ] zw_coproduct <- unique(zw_coproduct, by = c("measuredItemChildCPC", "zeroweight")) # We subset the zeroweight coproduct reference table by taking only zeroweights and their coproduct # that are childcommodities in the tree of the country zw_coproduct <- zw_coproduct[ measuredItemChildCPC %chin% data_tree$measuredItemChildCPC & zeroweight %chin% data_tree$measuredItemChildCPC ] # Computing information for non zeroweight commodities data_tree <- data_tree[measuredItemChildCPC %!in% zeroWeight] # this dataset will be used when creating processing share and shareUpdown dataComplete <- copy(data_tree) # Quantity of parent destined to the production of the given child (only for child with one parent for the moment) data_tree[, processed_to_child := ifelse(number_of_parent == 1, production_of_child, NA_real_)] # if a parent has one child, all the production of the child comes from that parent data_tree[ number_of_children == 1, processed_to_child := parent_qty_processed * extractionRate, processed_to_child ] data_tree[production_of_child == 0, processed_to_child := 0] # assigning the entired availability to processed for parent having only processed as utilization data_tree[ number_of_children == 1 & unique_proc == TRUE, processed_to_child := availability * extractionRate ] # mirror assignment for imputing processed quantity for multple parent children # 5 loop is sufficient to deal with all the cases for (k in 1:5) { data_tree <- RemainingToProcessedParent(data_tree) data_tree <- RemainingProdChildToAssign(data_tree) } data_tree <- RemainingToProcessedParent(data_tree) # proportional allocation of the remaing production of multiple parent children data_tree[, processed_to_child := ifelse( number_of_parent > 1 & is.na(processed_to_child), (remaining_to_process_child * is.na(processed_to_child) * remaining_processed_parent) / sum((remaining_processed_parent * is.na(processed_to_child)), na.rm = TRUE), processed_to_child), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] # Update of remaining production to assing ( should be zero for 2000:2013) data_tree[, parent_already_processed := ifelse( is.na(parent_qty_processed), parent_qty_processed, sum(processed_to_child / extractionRate,na.rm = TRUE) ), by = c("geographicAreaM49", "measuredItemParentCPC", "timePointYears") ] data_tree[, remaining_processed_parent := round(parent_qty_processed - parent_already_processed)] data_tree[ remaining_processed_parent < 0, remaining_processed_parent := 0 ] # Impute processed quantity for 2014 onwards using 3 years average # (this only to imput shareDownUp) # data_tree <- # data_tree[ # order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), # processed_to_child_avg := rollavg(processed_to_child, order = 3), # by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") # ] # # setkey(data_tree, NULL) # # data_tree[timePointYears > 2013 & is.na(processed_to_child), processed_to_child := processed_to_child_avg] # Back to zeroweight cases(we assign to zeroweights the processed quantity of their coproduct(already calculated)) zw_coproduct_bis <- merge( data_tree, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) zw_coproduct_bis[, `:=`( measuredItemChildCPC = zeroweight, processed_to_child = processed_to_child / extractionRate ) ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") zw_coproduct_bis <- zw_coproduct_bis[, c(sel_vars, "processed_to_child"), with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk zw_coproduct_bis[, processed_to_child := sum(processed_to_child, na.rm = TRUE), by = sel_vars ] zw_coproduct_bis <- unique(zw_coproduct_bis, by = colnames(zw_coproduct_bis)) data_zeroweight <- dt_left_join(data_zeroweight, zw_coproduct_bis, by = sel_vars) data_zeroweight[, processed_to_child := processed_to_child * extractionRate ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "number_of_parent", "parent_qty_processed", "production_of_child", "processed_to_child") data_zeroweight <- data_zeroweight[, sel_vars, with = FALSE] data_tree <- data_tree[, sel_vars, with = FALSE] #combining zeroweight and non zero weight commodities data_tree <- rbind(data_tree, data_zeroweight) #Correction #calculate ShareDownUp data_tree[, shareDownUp := processed_to_child / sum(processed_to_child, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemChildCPC", "timePointYears") ] #some corrections... data_tree[is.na(shareDownUp) & number_of_parent == 1, shareDownUp := 1] # data_tree[ # (production_of_child == 0 | is.na(production_of_child)) & # measuredItemChildCPC %!in% zeroWeight & # timePointYears < 2014, # shareDownUp := 0 # ] # # data_tree[ # (parent_qty_processed == 0 | is.na(parent_qty_processed)) & # timePointYears < 2014, # shareDownUp :=0 # ] data_tree[is.na(shareDownUp), shareDownUp := 0] data_tree[,share:=shareDownUp] data_tree <- unique( data_tree[geographicAreaM49 %!in% unique(shareUpDownTree$geographicAreaM49), c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "share"), with = FALSE ] ) # data_tree<-rbind(data_tree_f1,data_tree_f2) setDT(data_tree) # calculating shareUpdown for each child data_ShareUpDoawn <- dataComplete[, c("geographicAreaM49", "timePointYears", "measuredItemParentCPC", "availability", "parent_qty_processed", "measuredItemChildCPC", "extractionRate", "production_of_child", "number_of_children", "number_of_parent"), with = FALSE ] data_ShareUpDoawn <- unique( data_ShareUpDoawn, by = colnames(data_ShareUpDoawn) ) data_ShareUpDoawn <- merge( data_ShareUpDoawn, data_tree, by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears"), all = TRUE ) setnames(data_ShareUpDoawn,"share","shareDownUp") data_ShareUpDoawn <- data_ShareUpDoawn[measuredItemChildCPC %!in% zeroWeight] data_ShareUpDoawn[, shareUpDown := NA_real_] data_ShareUpDoawn[ !is.na(parent_qty_processed) & extractionRate>0, shareUpDown := (production_of_child / extractionRate) * shareDownUp / sum(production_of_child / extractionRate * shareDownUp, na.rm = TRUE), by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") ] data_ShareUpDoawn[is.nan(shareUpDown), shareUpDown := NA_real_] data_ShareUpDoawn[, shareUpDown:=ifelse( number_of_parent==1, shareUpDown / sum(shareUpDown[number_of_parent==1], na.rm = TRUE) * (1 - sum(shareUpDown[number_of_parent==1], na.rm = TRUE)), shareUpDown ), by = c("geographicAreaM49","timePointYears","measuredItemParentCPC") ] # data_ShareUpDoawn <- # data_ShareUpDoawn[ # order(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears), # shareUpDown_avg := rollavg(shareUpDown, order = 3), # by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC") # ] # # setkey(data_ShareUpDoawn, NULL) # # data_ShareUpDoawn[timePointYears > 2013, shareUpDown := shareUpDown_avg] # # data_ShareUpDoawn[, shareUpDown_avg := NULL] # # data_ShareUpDoawn[ # timePointYears > 2013, # shareUpDown := shareUpDown / sum(shareUpDown, na.rm = TRUE), # by = c("geographicAreaM49", "timePointYears", "measuredItemParentCPC") # ] sel_vars <- c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "shareUpDown") data_ShareUpDoawn_final <- data_ShareUpDoawn[, sel_vars, with = FALSE] shareUpDown_zeroweight <- merge( data_ShareUpDoawn_final, zw_coproduct, by = "measuredItemChildCPC", allow.cartesian = TRUE, all.y = TRUE ) shareUpDown_zeroweight[, measuredItemChildCPC := zeroweight] shareUpDown_zeroweight <- shareUpDown_zeroweight[, sel_vars, with = FALSE] # Correction to milk tree issue ( zeroweight can be associated with 2 main products from the same parent) # example: butter of cow milk shareUpDown_zeroweight<- shareUpDown_zeroweight[, shareUpDown := sum(shareUpDown, na.rm = TRUE), by = c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears") ] shareUpDown_zeroweight <- unique( shareUpDown_zeroweight, by = colnames(shareUpDown_zeroweight) ) # /correction data_ShareUpDoawn_final <- rbind(data_ShareUpDoawn_final, shareUpDown_zeroweight) # some correction data_ShareUpDoawn_final[is.na(shareUpDown), shareUpDown := 0] data_ShareUpDoawn_final[!is.na(shareUpDown), flagObservationStatus := "I"] data_ShareUpDoawn_final[!is.na(shareUpDown), flagMethod := "c"] # setnames(data_ShareUpDoawn_final,"measuredItemChildCPC","measuredElementSuaFbs") data_ShareUpDoawn_final[,measuredElementSuaFbs:="shareUpDown"] data_ShareUpDoawn_final[,flagObservationStatus:=NULL] data_ShareUpDoawn_final[,flagMethod:=NULL] data_ShareUpDoawn_final<-data_ShareUpDoawn_final[,colnames(shareUpDownTree),with=FALSE] data_ShareUpDoawn_final<-unique(data_ShareUpDoawn_final,by=colnames(shareUpDownTree),with=FALSE) shareUpDownTree<-rbind( shareUpDownTree, data_ShareUpDoawn_final[!shareUpDownTree, on=c("geographicAreaM49")] ) ######END NEW WAY TO GENERATE SHAREDOWNUP------------------------------------------------- message("Calculating shareDownUps...") #Using the whole tree not by level # if (nrow(shareUpDownTree)>0){ ExtrRate <- tree[ !is.na(Value) & measuredElementSuaFbs == 'extractionRate' & geographicAreaM49 %in% unique(shareUpDownTree$geographicAreaM49) ][, list( measuredItemParentCPC, geographicAreaM49, measuredItemChildCPC, timePointYears, extractionRate = Value ) ] data_tree <- data[measuredElementSuaFbs %chin% c('foodManufacturing') & geographicAreaM49 %in% unique(shareUpDownTree$geographicAreaM49)] # setnames(data_tree, "measuredItemFbsSua", "measuredItemParentCPC") data_tree <- merge( data_tree[,list(geographicAreaM49,timePointYears, ProcessedParent=Value, measuredItemParentCPC=measuredItemSuaFbs)], ExtrRate, by = c(params$parentVar, params$geoVar, params$yearVar), allow.cartesian = TRUE, all.y = TRUE ) data_tree<-as.data.table(data_tree) #dataset to calculate the number of parent of each child and the number of children of each parent #including zeroweight commodities data_count<-unique( data_tree[, .(geographicAreaM49,measuredItemParentCPC,measuredItemChildCPC,timePointYears)], by=c("geographicAreaM49","measuredItemParentCPC","measuredItemChildCPC","timePointYears") ) #Caculate the number of parent of each child data_count[,number_of_parent:=.N, by=c("geographicAreaM49","measuredItemChildCPC","timePointYears") ] # #calculate the number of children of each parent data_count[measuredItemChildCPC %!in% zeroWeight,number_of_children:=uniqueN(measuredItemChildCPC), by=c("geographicAreaM49","measuredItemParentCPC","timePointYears") ] data_tree<-merge( data_tree, data_count, by = c(params$parentVar,params$childVar, params$geoVar, params$yearVar), allow.cartesian = TRUE, all.x = TRUE ) data_tree<-data_tree[,list(geographicAreaM49,measuredItemParentCPC,measuredItemChildCPC, timePointYears,extractionRate,ProcessedParent, number_of_parent,number_of_children)] data_tree<-unique(data_tree,by=c(colnames(data_tree))) #dataset containing the production of child commodities # dataprodchild <- dataSuaUn[measuredElementSuaFbs %chin% c('production')] dataprodchild <- data[measuredElementSuaFbs %chin% c('production') & geographicAreaM49 %chin% unique(shareUpDownTree$geographicAreaM49)] # setnames(dataprodchild, "measuredItemFbsSua", "measuredItemChildCPC") setnames(dataprodchild, "measuredItemSuaFbs", "measuredItemChildCPC") dataprodchild<- unique( dataprodchild[,list(geographicAreaM49,measuredItemChildCPC, timePointYears,Value,flagObservationStatus, flagMethod)], by=c("geographicAreaM49","measuredItemChildCPC","timePointYears", "Value","flagObservationStatus","flagMethod") ) setnames(dataprodchild, "Value", "production_of_child") data_tree<-merge( data_tree, dataprodchild, by=c(params$geoVar,params$childVar,params$yearVar), all.x = TRUE ) data_tree<-merge( data_tree, shareUpDownTree, by=c(params$geoVar,params$parentVar, params$childVar,params$yearVar), all.x = TRUE ) data_tree<-data_tree[timePointYears>2013] data_tree[,shareDownUp:=(ProcessedParent*shareUpDown*extractionRate)/ sum(ProcessedParent*shareUpDown*extractionRate,na.rm = TRUE), by=c(params$geoVar,params$childVar,params$yearVar) ] data_tree[is.na(shareDownUp) & number_of_parent==1,shareDownUp:=1] data_tree[is.na(shareDownUp),shareDownUp:=0] data_tree[,share:=shareDownUp] data_tree[,shareDownUp:=NULL] data_tree<-unique( data_tree[, list(geographicAreaM49, measuredItemParentCPC, measuredItemChildCPC, timePointYears, share) ], by=c("geographicAreaM49", "measuredItemParentCPC", "measuredItemChildCPC", "timePointYears", "share") ) setDT(data_tree) # # } else { # # data_tree_f1 <- # data.table( # geographicAreaM49 = character(), # timePointYears = character(), # measuredItemParentCPC = character(), # measuredItemChildCPC = character(), # share = numeric() # ) # } ############################################################## ######### SUGAR RAW CODES TO BE CONVERTED IN 2351F ########### ############################################################## data=convertSugarCodes(data) ############################################################## ############### CREATE THE COLUMN "OFFICIAL" ################# ############################################################## flagValidTable = ReadDatatable("valid_flags") data=left_join(data,flagValidTable,by=c("flagObservationStatus","flagMethod"))%>% data.table data[flagObservationStatus%in%c("","T"),Official:=TRUE] data[is.na(Official),Official:=FALSE] data[flagObservationStatus%in%c("","T"),Protected:=TRUE] ####################################### # The following copy is needed for saving back some of the intermediate # files. These intermediate steps will come without flag and the flag # will be merged with this original data object dataFlags = copy(data) ############################################################## # For DERIVED select only the protected and the estimation # (coming from the submodule of derived and Livestock) # I have to select Protected and Estimation (I,e) and (I,i) # For all the others delete the production value # this will leave the Sua Filling creting prodcution, where needed level = findProcessingLevel(tree, from = params$parentVar, to = params$childVar, aupusParam = params) primaryEl = level[processingLevel == 0, get(params$itemVar)] data[!(get(params$protected)=="TRUE"|(flagObservationStatus=="I"&flagMethod%in%c("i","e"))) &get(params$elementVar)==params$productionCode &!(get(params$itemVar) %in% primaryEl),Value:=NA] p=params ############################################################## ############## LAST MANIPULATIONS ON TREE ################# ############################################################## tree[,c("flagObservationStatus","flagMethod"):=NULL] tree=data.table(dcast(tree,geographicAreaM49 + measuredItemParentCPC + measuredItemChildCPC + timePointYears ~ measuredElementSuaFbs,value.var = "Value")) tree=tree[!is.na(extractionRate)] tree=tree[!is.na(measuredItemChildCPC)] tree=tree[,share:=NULL] tree<-merge( tree, data_tree, by=c(params$geoVar,params$parentVar,params$childVar,params$yearVar) ) message("Download fbsTree from SWS...") fbsTree=ReadDatatable("fbs_tree") fbsTree=data.table(fbsTree) setnames(fbsTree,colnames(fbsTree),c( "fbsID1", "fbsID2", "fbsID3","fbsID4", "measuredItemSuaFbs")) setcolorder(fbsTree,c("fbsID4", "measuredItemSuaFbs", "fbsID1", "fbsID2", "fbsID3")) #some correction fbsTree<-fbsTree[measuredItemSuaFbs %in% c("34120","21932.02"),fbsID4:="2586"] treeFBSmerge<-NonStandardizedChidren(fbsTree = fbsTree,tree = tree,standParams = p) #Sumeda treeFBSmerge <- treeFBSmerge[is.na(standard_child), standard_child := FALSE] tree<-merge( tree, treeFBSmerge, by=c(params$geoVar,params$parentVar,params$childVar,params$yearVar) ) tree<-tree[timePointYears %in% yearVals,] data = data[!is.na(measuredElementSuaFbs), ] data=data[,c("measuredItemSuaFbs", "measuredElementSuaFbs", "geographicAreaM49", "timePointYears", "Value", "flagObservationStatus", "flagMethod", "Valid", "Protected", "Official"),with=FALSE] ####################################################### data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","flagObservationStatus","flagMethod"))] # data=data[,mget(c("measuredItemSuaFbs","measuredElementSuaFbs", "geographicAreaM49", "timePointYears","Value","Official","Protected","type"))] ############################################################# ########## LOAD NUTRIENT DATA AND CORRECT ############# ############################################################# message("Loading nutrient data...") itemKeys = GetCodeList("agriculture", "aupus_ratio", "measuredItemCPC")[, code] # Nutrients are: # 1001 Calories # 1003 Proteins # 1005 Fats nutrientCodes = c("1001", "1003", "1005") nutrientData = getNutritiveFactors(measuredElement = nutrientCodes, timePointYears = as.character(2014:2018), geographicAreaM49 = COUNTRY ) setnames(nutrientData, c("measuredItemCPC", "timePointYearsSP"), c("measuredItemSuaFbs", "timePointYears")) # It has been found that some Nutrient Values are wrong in the Nutrient Data Dataset ######### CREAM SWEDEN nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1001",Value:=195] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1003",Value:=3] nutrientData[geographicAreaM49=="752"&measuredItemSuaFbs=="22120"&measuredElement=="1005",Value:=19] ### MILK SWEDEN nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1001",Value:=387] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1003",Value:=26] nutrientData[geographicAreaM49%in%c("756","300","250","372","276")&measuredItemSuaFbs=="22251.01"&measuredElement=="1005",Value:=30] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1001",Value:=310] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1003",Value:=23] nutrientData[geographicAreaM49=="300"&measuredItemSuaFbs=="22253"&measuredElement=="1005",Value:=23] setnames(nutrientData,"measuredElement","measuredElementSuaFbs") nutrientData[get(params$elementVar)=="1001",params$elementVar:=params$calories] nutrientData[get(params$elementVar)=="1003",params$elementVar:=params$proteins] nutrientData[get(params$elementVar)=="1005",params$elementVar:=params$fats] ############################ POPULATION ##################################### key <- DatasetKey( domain = "population", dataset = "population_unpd", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = COUNTRY), measuredElementSuaFbs = Dimension(name = "measuredElement", keys = "511"), # 511 = Total population timePointYears = Dimension(name = "timePointYears", keys = as.character(2000:2018)) ) ) popSWS <- GetData(key) stopifnot(nrow(popSWS) > 0) popSWS[geographicAreaM49 == "156", geographicAreaM49 := "1248"] # Fix for missing regional official data in the country total # Source: DEMOGRAPHIC SURVEY, Kurdistan Region of Iraq, July 2018, IOM UN Migration # ("the KRI population at 5,122,747 individuals and the overall Iraqi # population at 36,004,552 individuals", pag.14; it implies 14.22805%) # https://iraq.unfpa.org/sites/default/files/pub-pdf/KRSO%20IOM%20UNFPA%20Demographic%20Survey%20Kurdistan%20Region%20of%20Iraq_0.pdf popSWS[geographicAreaM49 == "368" & timePointYears %in% 2014:2018, Value := Value * 0.8577195] ############################ / POPULATION ################################## # # Calculate calories calories_per_capita <- merge( # Food data[ measuredElementSuaFbs == "food", list( geographicAreaM49, # measuredElementSuaFbs = "664", measuredItemSuaFbs, timePointYears, food = Value #, # flagObservationStatus = "T", # flagMethod = "i" ) ], # Calories nutrientData[, list( geographicAreaM49, measuredItemSuaFbs, #= measuredItemCPC, timePointYears, #= timePointYearsSP, measuredElementSuaFbs, nutrient = Value ) ], by = c('geographicAreaM49', 'timePointYears', 'measuredItemSuaFbs'), all.x = TRUE, allow.cartesian = TRUE ) # calories_per_capita <- merge( calories_per_capita, popSWS[, list(geographicAreaM49, timePointYears, population = Value)], by = c('geographicAreaM49', 'timePointYears'), all.x = TRUE ) #calories_per_capita[, Protected := FALSE] calories_per_capita[, flagObservationStatus := "T"] calories_per_capita[, flagMethod := "I"] calories_per_capita_total<-copy(calories_per_capita) calories_per_capita[, Value := food * nutrient / population / 365 * 10] calories_per_capita[, c("food", "nutrient", "population") := NULL] # calories_per_capita_total<-copy(calories_per_capita) calories_per_capita_total[, Value := food * nutrient/100] calories_per_capita_total[, c("food", "nutrient", "population") := NULL] calories_per_capita_total[measuredElementSuaFbs=="calories", measuredElementSuaFbs:="TotalCalories"] calories_per_capita_total[measuredElementSuaFbs=="proteins", measuredElementSuaFbs:="TotalProteins"] calories_per_capita_total[measuredElementSuaFbs=="fats", measuredElementSuaFbs:="TotalFats"] dataDes<-rbind(calories_per_capita,calories_per_capita_total) ################################################################# ################################################################# ################################################################# message("Download Utilization Table from SWS...") #utilizationTable=ReadDatatable("utilization_table") Utilization_Table <- ReadDatatable("utilization_table_2018") DerivedItem <- Utilization_Table[derived == 'X', get("cpc_code")] message("Download zero Weight from SWS...") zeroWeight=ReadDatatable("zero_weight")[,item_code] message("Defining vectorized standardization function...") ## Split data based on the two factors we need to loop over uniqueLevels = data[, .N, by = c("geographicAreaM49", "timePointYears")] uniqueLevels[, N := NULL] parentNodes = getCommodityLevel(tree, parentColname = "measuredItemParentCPC", childColname = "measuredItemChildCPC") parentNodes = parentNodes[level == 0, node] aggFun = function(x) { if (length(x) > 1) stop("x should only be one value!") return(sum(x)) } standData = vector(mode = "list", length = nrow(uniqueLevels)) standData0 = vector(mode = "list", length = nrow(uniqueLevels)) standQTY=vector(mode = "list", length = nrow(uniqueLevels)) NonStanditemChild = vector(mode = "list", length = nrow(uniqueLevels)) onlyCalories<-c("39120.01","23140.01","23220.02","39130.01","39120.02","39120.03", "23120.02","23140.06","39120.04","39130.02", "39120.05","39120.06", "39120.07","39120.08","39120.09","39120.10","39120.11","39120.12","39120.13", "23180","23999.02","23540","39120.14","22130.01","22290","22270","23993.01") #########STANDARDIZATION AND AGGREGATION----------------------------------- message("Beginning actual standardization process...") # for (i in seq_len(nrow(uniqueLevels))) { #i=4 message(paste("Standardizing ",uniqueLevels$geographicAreaM49[i]," for the year ",uniqueLevels$timePointYears[i])) filter = uniqueLevels[i, ] dataSubset = data[filter, , on = c("geographicAreaM49", "timePointYears")] dataDesSubset = dataDes[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset = tree[filter, , on = c("geographicAreaM49", "timePointYears")] treeSubset[, c("geographicAreaM49", "timePointYears") := NULL] # there some cases where the multiparent child commodity have 2 parents and is in the FBS # group than only 1 parent. In that case it is comnsidered as standardized (even if for the other parent it will be false) # it is the case starch of potaote that has 2 parent: potaote ans sweet potatoe but is the same FBS group than potatoe nonStandChildren<-treeSubset[,som:=sum(standard_child,na.rm = TRUE), by=c("measuredItemChildCPC")] nonStandChildren<-unique( nonStandChildren[,list(measuredItemChildCPC,som,standard_child)], by=c("measuredItemChildCPC","som","standard_child") ) #keep only child commodities that should not be standardized nonStandChildren<-nonStandChildren[som==0 & !is.na(standard_child)] nonStandChildren[,som:=NULL] nonStandChildren<-nonStandChildren [,get(p$childVar)] #cottonseet is not a promary in the tree but is the only commodity in the FBS group Cottonseed nonStandChildren<-c(nonStandChildren,"0143") # nonStandChildren<-NonStandardizedChidren(fbsTree = fbsTree,tree = treeSubset,standParams = p) #************************************ #child items that are not standardized #Items being alone in FBS groups OneItemFBS<-fbsTree[,number_item:=.N, by=c("fbsID4")][number_item==1,get("measuredItemSuaFbs")] #Palm oil issue(indonesia) OneItemFBS<-c(OneItemFBS,"2165") parentNod<-setdiff(treeSubset[,get(p$parentVar)],treeSubset[,get(p$childVar)]) parentNod<-c(parentNod,nonStandChildren) NonStandItems<-dataSubset[get(p$itemVar) %!in% parentNod & get(p$itemVar) %in% DerivedItem & get(p$itemVar) %!in% treeSubset[,get(p$childVar)] & get(p$itemVar) %in% fbsTree[,get(p$itemVar)] & abs(Value)>1] NonStandItems<-unique(NonStandItems[,get(p$itemVar)]) NonStanditemChild[[i]]=as.data.table(cbind(geographicAreaM49=dataSubset$geographicAreaM49[1], measuredItemSuaFbs=NonStandItems, timePointYears=dataSubset$timePointYears[1])) #message("Download cut Items from SWS...") #cutItems=ReadDatatable("cut_items2")[,cpc_code] treeSubset[,weight:=1] treeSubset[measuredItemChildCPC %in% zeroWeight , weight:=0] treeSubset[measuredItemChildCPC %in% onlyCalories , weight:=0] #************************************** #data<-dataSubset #tree<-treeSubset standParams<-p sugarHack<-FALSE specificTree<-FALSE #cut<-cutItems #additiveElements<-nutrientElements keyCols = standParams$mergeKey[standParams$mergeKey != standParams$itemVar] if(!specificTree){ if(nrow(dataSubset[, .N, by = c(standParams$geoVar, standParams$yearVar)]) > 1) stop("If not using a specificTree, there should only be one ", "country and year!") keyCols = keyCols[!keyCols %in% c(standParams$geoVar, standParams$yearVar)] treeSubset[, c(standParams$yearVar) := dataSubset[, get(standParams$yearVar)][1]] treeSubset[, c(standParams$geoVar) := dataSubset[, get(standParams$geoVar)][1]] } if(dim(treeSubset)[1]!=0){ standTree = collapseEdges_NEW(edges = treeSubset, keyCols = keyCols, parentName = standParams$parentVar, childName = standParams$childVar, extractionName = standParams$extractVar,notStandChild = nonStandChildren) standTree[,weight:=1] standTree[measuredItemChildCPC %in% zeroWeight , weight:=0] standTree[measuredItemParentCPC %in% zeroWeight , weight:=0] }else{ standTree = treeSubset } #new to standardize quantity dataTest<-copy(dataSubset) standKey = standParams$mergeKey[standParams$mergeKey != standParams$itemVar] treeTest = collapseEdges_NEW(edges = treeSubset, parentName = standParams$parentVar, childName = standParams$childVar, extractionName = standParams$extractVar, keyCols = standKey, notStandChild = nonStandChildren) #build a function that take: # treesubset, # datasubset, # datadessubset # function name : standardization standardization<-function(dataQTY=dataSubset, dataDES=dataDesSubset, standTree=treeTest, params=standParams){ #TO DO: quality controle with stopifnot StandtreeQTY<-copy(standTree) StandtreeDES<-copy(standTree) ## Merge the tree with the node data StandtreeQTY[, c(params$parentVar, params$childVar, params$yearVar, params$geoVar) := list(as.character(get(params$parentVar)), as.character(get(params$childVar)), as.character(get(params$yearVar)), as.character(get(params$geoVar)))] #correction of some weight (in principale this should be done in the SUA caluclation) # StandtreeQTY[get(params$childVar)=="22241.01",weight:=1] #Butter of cow milk # StandtreeQTY[get(params$childVar)=="22120",weight:=1] #Cream fresh setnames(dataQTY, params$itemVar, params$childVar) dataQTY <-merge( dataQTY, StandtreeQTY, by = c(params$yearVar, params$geoVar, params$childVar), all.x = TRUE, allow.cartesian = TRUE ) dataQTY[is.na(get(params$parentVar)) & get(params$childVar) %!in% zeroWeight, c(params$parentVar, params$extractVar, params$shareVar,"weight") := list(get(params$childVar), 1, 1,1)] #zeroweight that are not in the tree shoulg have weight 0 so thet they will not be standardized # case of bran of pulse(paraguay) dataQTY[is.na(get(params$parentVar)) & get(params$childVar) %in% zeroWeight, c(params$parentVar, params$extractVar, params$shareVar,"weight") := list(get(params$childVar), 1, 1,0)] dataQTY[get(params$childVar) %in% onlyCalories, weight:=0] #Cut this connection for Korea dataQTY[get(params$childVar)=="24230.01", share:=0] dataQTY_pprocessed<-dataQTY[standard_child==FALSE & get(params$elementVar)==c(params$productionCode)] dataQTY_pprocessed[,params$elementVar:=params$foodProcCode] #If the parent is a zerweight change the weight of the child to 0 # Issue find in Germany, child of molasses were standardized dataQTY_pprocessed[get(params$parentVar) %in% zeroWeight,weight:=0] # dataQTY_pprocessed[get(params$parentVar) %in% "0111" & # get(params$childVar) %in% "24310.01",weight:=0] outDataQTY<-dataQTY_pprocessed[, list( Value = sum( Value*weight /get(params$extractVar)*get(params$shareVar), na.rm = TRUE)), by = c(params$yearVar, params$geoVar,params$elementVar, params$parentVar)] #For commodities that are alone in their FBS group, we keep their proces as it is dataQTY_procPar<-copy(dataQTY) dataQTY_procPar<-dataQTY[, c(params$geoVar,params$childVar, params$elementVar,params$yearVar,"Value"), with=FALSE ] setnames(dataQTY_procPar,params$childVar,params$itemVar) dataQTY_procPar[,`:=`(Value.par=Value,Value=NULL)] dataQTY_procPar<-unique(dataQTY_procPar, by=colnames(dataQTY_procPar)) setnames(dataQTY_procPar,params$itemVar,params$parentVar) outDataQTY<-merge( outDataQTY, dataQTY_procPar, by=c(params$geoVar,params$parentVar,params$elementVar,params$yearVar), all.x = TRUE ) outDataQTY[get(params$elementVar)==params$foodProcCode & get(params$parentVar) %in% OneItemFBS, Value:=Value.par] outDataQTY[,Value.par:=NULL] #------------------------- dataQTY_other<-dataQTY[ get(params$elementVar)!=params$foodProcCode] dataQTY_other[get(params$childVar) %in% nonStandChildren, #TO DO: add nonStandChildren to the arguments c(params$parentVar, params$extractVar, params$shareVar,"weight") := list(get(params$childVar), 1, 1,1)] dataQTY_other<-unique( dataQTY_other,by=colnames(dataQTY) ) #WEIGH correction dataQTY_other[get(params$childVar) %!in% nonStandChildren & standard_child==FALSE, weight:=0] dataQTY_other[get(params$childVar) %in% onlyCalories, weight:=0] dataQTY_other[get(params$parentVar) %in% zeroWeight[! zeroWeight %in% c("22120","22241.01")], weight:=0] outDataQTY_other = dataQTY_other[, list( Value = sum( Value*weight /get(params$extractVar)*get(params$shareVar), na.rm = TRUE)), by = c(params$yearVar, params$geoVar,params$elementVar, params$parentVar)] dataQTY_prod<-copy(dataSubset) dataQTY_prod<-dataQTY[, c(params$geoVar,params$childVar, params$elementVar,params$yearVar,"Value"), with=FALSE ] setnames(dataQTY_prod,params$childVar,params$itemVar) dataQTY_prod[,`:=`(Value.par=Value,Value=NULL)] dataQTY_prod[get(params$itemVar) %in% zeroWeight[! zeroWeight %in% c("22120","22241.01")], Value.par:=0] dataQTY_prod<-unique(dataQTY_prod, by=colnames(dataQTY_prod)) setnames(dataQTY_prod,params$itemVar,params$parentVar) outDataQTY_other<-merge( outDataQTY_other, dataQTY_prod, by=c(params$geoVar,params$parentVar,params$elementVar,params$yearVar), all.x = TRUE ) outDataQTY_other[get(params$elementVar)==params$productionCode, Value:=Value.par] #do not change the process of items that are alone outDataQTY_other[get(params$elementVar)==params$foodProcCode & get(params$parentVar) %in% OneItemFBS, Value:=Value.par] outDataQTY_other[,Value.par:=NULL] outDataQTY<- outDataQTY[, c(params$geoVar,params$parentVar,params$elementVar,params$yearVar,"Value"), with=FALSE] outDataQTY_other<- outDataQTY_other[, c(params$geoVar,params$parentVar,params$elementVar,params$yearVar,"Value"), with=FALSE ] #DES AGGREGATION ## Merge the tree with the node data StandtreeDES[, c(params$parentVar, params$childVar, params$yearVar, params$geoVar) := list(as.character(get(params$parentVar)), as.character(get(params$childVar)), as.character(get(params$yearVar)), as.character(get(params$geoVar)))] setnames(dataDES, params$itemVar, params$childVar) dataDES<-merge(dataDES, StandtreeDES, by = c(params$yearVar, params$geoVar, params$childVar), all.x = TRUE, allow.cartesian = TRUE) dataDES[is.na(get(params$parentVar)) | get(params$childVar)%in% nonStandChildren, c(params$parentVar, params$extractVar, params$shareVar) := list(get(params$childVar), 1, 1)] dataDES[,missedDES:=mean(Value,na.rm = TRUE)>0 & sum(share,na.rm = TRUE)==0, by = c(params$yearVar, params$geoVar, params$childVar,params$elementVar) ] dataDES[get(params$childVar) %in% nonStandChildren | missedDES==TRUE, `:=`(measuredItemParentCPC=measuredItemChildCPC,share=1, standard_child=FALSE)] dataDES[,weight:=1] dataDES[,params$extractVar:=1] dataDES<-unique( dataDES,by=names(dataDES) ) outDataDes = dataDES[, list( Value = sum( Value*get(params$shareVar), na.rm = TRUE)), by = c(params$yearVar, params$geoVar, params$parentVar,params$elementVar)] outDataDes<-outDataDes[,c(colnames(outDataQTY)),with=FALSE] out = rbind(outDataQTY,outDataQTY_other,outDataDes) setnames(out,params$parentVar,params$itemVar) #Standardized file standardizeQty<-rbind(dataQTY_other,dataQTY_pprocessed) standardizeQty<-standardizeQty[,list(geographicAreaM49,timePointYears,measuredItemParentCPC, measuredItemChildCPC,measuredElementSuaFbs, Value,flagObservationStatus,flagMethod,extractionRate,share, standard_child,weight,Stand_Value=Value/extractionRate*share*weight)] output<-list(fbs=out,stand=standardizeQty) return(output) } output=standardization(dataSubset,dataDesSubset,treeTest,standParams) out=output$fbs standData0[[i]] <- out standQTY[[i]] <- output$stand # STEP 7: Aggregate to FBS Level if(is.null(fbsTree)){ # If no FBS tree, just return SUA-level results outOut=dataSubset } else { outOut = computeFbsAggregate(data =out , fbsTree = fbsTree, standParams = p) } standData[[i]] <- rbindlist(outOut) names(standData[[i]])[grep("^fbsID", names(standData[[i]]))] <- params$itemVar standData[[i]][,(params$itemVar):= paste0("S", get(params$itemVar))] } ##############ITEMS THAT ARE NOT STANDARDIZED################################################## standQTY<-rbindlist(standQTY) NonStanditemChild<-rbindlist(NonStanditemChild) NonStanditemChild<-unique(NonStanditemChild[,list(geographicAreaM49,measuredItemSuaFbs)], by=c(p$geoVar,p$itemVar)) setnames(NonStanditemChild,"measuredItemSuaFbs","measuredItemFbsSua") NonStanditemChild<-nameData("suafbs", "sua_balanced", NonStanditemChild) #if the number of SUAs is more than 1 we cannot include COUNTRY_NAME, in the file name if(length(selectedGEOCode)==1){ tmp_file_nonStandItemps<- tempfile(pattern = paste0("NON_STANDARDIZED_ITEMS_", COUNTRY_NAME, "_"), fileext = '.csv') }else{ tmp_file_nonStandItemps<- tempfile(pattern = paste0("NON_STANDARDIZED_ITEMS_", "_"), fileext = '.csv')} write.csv(NonStanditemChild, tmp_file_nonStandItemps) ############################################################################################ # XXX fix this codes <- tibble::tribble( ~code, ~name, "5910", "exports", "5520", "feed", "5141", "food", "5023", "foodManufacturing", "5610", "imports", "5165", "industrial", "5016", "loss", "5510", "production", "5525", "seed", "5071", "stock", "664", "calories", "674", "proteins", "684", "fats", "5166", "residual", "5164", "tourist", "261", "TotalCalories", "271", "TotalProteins", "281", "TotalFats" ) setDT(codes) #####sSAVING FBS STANDARDIZED#########################################---------------------------- fbs_standardized<-rbindlist(standData0) fbs_standardized[,`:=`(flagObservationStatus="I", flagMethod="s")] setnames(fbs_standardized,"measuredItemSuaFbs","measuredItemFbsSua") setDT(fbs_standardized) fbsstand_residual<-copy(fbs_standardized) calculateImbalance(data=fbsstand_residual,keep_supply = FALSE,keep_utilizations = FALSE) fbsstand_residual[,`:=`(Value=imbalance, measuredElementSuaFbs="residual", imbalance=NULL)] fbsstand_residual<-unique(fbsstand_residual, by=colnames(fbsstand_residual)) fbs_standardized<-rbind(fbs_standardized[measuredElementSuaFbs %!in% c("residual")],fbs_standardized) fbs_standardized <- fbs_standardized[codes, on = c('measuredElementSuaFbs' = 'name')] fbs_standardized[,measuredElementSuaFbs:=code] fbs_standardized[,code:=NULL] fbs_standardized[is.na(Value),flagObservationStatus:=NA] fbs_standardized[is.na(Value),flagMethod:=NA] fbs_standardized<-fbs_standardized[measuredElementSuaFbs %!in% c("261","271","281")] #Food grams #ADD food supply (Grams/capita/day) in FBS standardized foodGram_data <- dt_left_join( # Food fbs_standardized[ measuredElementSuaFbs == '5141', list( geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs, timePointYears, food = Value, flagObservationStatus = "T", flagMethod = "i" ) ], # Population popSWS[, list(geographicAreaM49, timePointYears, population = Value)], by = c('geographicAreaM49', 'timePointYears') ) foodGram_data[,Value:=(food*1000000)/(365*population*1000)] foodGram_data[,measuredElementSuaFbs:="665"] foodGram_data[, c("food", "population") := NULL] foodGram_data<-foodGram_data[,list(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears,Value,flagObservationStatus,flagMethod)] fbs_standardized<-rbind(fbs_standardized,foodGram_data) message("saving FBS standardized...") SaveData(domain = "suafbs", dataset = "fbs_standardized", data = fbs_standardized, waitTimeout = 20000) #end fns standardized------------------------------------------------------------- ########SAVING FBS BALANCED#################################################------------------- fbs_balanced<-rbindlist(standData) fbs_balanced[,`:=`(flagObservationStatus="I", flagMethod="s")] setnames(fbs_balanced,"measuredItemSuaFbs","measuredItemFbsSua") #calculate imbalance for fbs and put it the residual and othe ruses fbs_residual<-copy(fbs_balanced) #fbs_residual<-fbs_residual[measuredItemFbsSua %!in% c("S2901","S2903","S2941")] fbs_residual<-fbs_residual[measuredItemFbsSua %!in% c("S2901")] calculateImbalance(data=fbs_residual,keep_supply = TRUE,keep_utilizations = FALSE) fbs_residual<- fbs_residual[!is.na(imbalance),list(geographicAreaM49,timePointYears, measuredItemFbsSua,supply,imbalance)] fbs_residual<-unique(fbs_residual,by=c(colnames(fbs_residual))) fbs_residual[,imbalance_percentage:=round(imbalance/supply*100,2)] fbs_residual1<-copy(fbs_balanced) calculateImbalance(data=fbs_residual1,keep_supply = FALSE,keep_utilizations = FALSE) fbs_residual1[,`:=`(Value=imbalance, measuredElementSuaFbs="residual", imbalance=NULL)] fbs_residual1<-unique(fbs_residual1, by=colnames(fbs_residual1)) fbs_balanced<-rbind(fbs_balanced[measuredElementSuaFbs %!in% c("residual")],fbs_residual1) fbs_balanced <- fbs_balanced[codes, on = c('measuredElementSuaFbs' = 'name')] fbs_balanced[,measuredElementSuaFbs:=code] fbs_balanced[,code:=NULL] fbs_balanced[is.na(Value),flagObservationStatus:=NA] fbs_balanced[is.na(Value),flagMethod:=NA] popData<- popSWS[,list(geographicAreaM49, timePointYears, measuredElementSuaFbs=measuredElement, measuredItemFbsSua="S2501", Value, flagObservationStatus, flagMethod)] popData<-popData[timePointYears %in% unique(fbs_balanced$timePointYears)] #correct process at FBS level Item_with_unbalanced <- data[measuredElementSuaFbs == "residual"] Item_with_unbalanced <- Item_with_unbalanced[abs(round(Value,0)) > 5000] Item_with_unbalanced<-merge( Item_with_unbalanced, fbsTree, by=c(p$itemVar), allow.cartesian = TRUE, all.x = TRUE ) Item_with_unbalanced<-Item_with_unbalanced[!is.na(fbsID4) & (measuredItemSuaFbs %!in% onlyCalories), list(geographicAreaM49,timePointYears, measuredItemFbsSua=paste0("S",fbsID4), cpc_unbalanced=measuredItemSuaFbs) ] Item_with_unbalanced<-unique(Item_with_unbalanced,by=c(colnames(Item_with_unbalanced))) if (nrow(Item_with_unbalanced) > 0) { Item_with_unbalanced<-aggregate( cpc_unbalanced ~ geographicAreaM49+measuredItemFbsSua+timePointYears, Item_with_unbalanced, paste0, collapse = "; ") setDT(Item_with_unbalanced) } else { Item_with_unbalanced <- data.table( geographicAreaM49 = character(), measuredItemFbsSua = character(), timePointYears = character(), measuredItemSuaFbs = character(), cpc_unbalanced = logical() ) } fbs_balanced_bis<-merge( fbs_balanced, Item_with_unbalanced, by=c(p$geoVar,p$yearVar, "measuredItemFbsSua"), all.x = TRUE ) fbs_balanced_bis[, IsSUAbal := ifelse(is.na(cpc_unbalanced), TRUE, FALSE)] fbs_balanced_bis<-merge( fbs_balanced_bis, fbs_residual[,list(geographicAreaM49,timePointYears,measuredItemFbsSua,imbalance=round(imbalance,0))], all.x = TRUE ) fbsid4<-paste0("S",unique(fbsTree$fbsID4)) fbs_balanced_bis[measuredItemFbsSua %!in% fbsid4,IsSUAbal:=FALSE] fbs_balanced_bis<-fbs_balanced_bis[!is.na(Value)] fbs_balanced_bis[,update_balance:=FALSE] fbs_balanced_bis[measuredElementSuaFbs %in% c("5023") & !is.na(imbalance) & !is.na(Value), update_balance:=ifelse(IsSUAbal==TRUE & Value+imbalance >0,TRUE,FALSE), by=c(p$geoVar,p$yearVar,"measuredItemFbsSua")] fbs_balanced_bis[measuredElementSuaFbs=="5023" , Value:=ifelse(update_balance==TRUE ,Value+imbalance,Value), by=c(p$geoVar,p$yearVar,"measuredItemFbsSua")] fbs_balanced_bis[measuredElementSuaFbs %in% c("5023","5166"), update_balance:=update_balance[measuredElementSuaFbs=="5023"], by=c(p$geoVar,p$yearVar,"measuredItemFbsSua")] fbs_balanced_bis<-fbs_balanced_bis[!is.na(Value)] fbs_balanced_bis[measuredElementSuaFbs=="5166" , Value:=ifelse(update_balance==TRUE ,0,Value), by=c(p$geoVar,p$yearVar,"measuredItemFbsSua")] fbs_balanced_bis<-fbs_balanced_bis[,names(fbs_balanced),with=FALSE] #correct other level fbstree_otherlev<-copy(fbsTree) fbstree_otherlev[,c("measuredItemSuaFbs","number_item"):=NULL] fbstree_otherlev<-unique(fbstree_otherlev) setnames(fbstree_otherlev,"fbsID4","measuredItemFbsSua") fbstree_otherlev[, measuredItemFbsSua :=paste0("S",measuredItemFbsSua)] fbstree_otherlev[, fbsID1 :=paste0("S",fbsID1)] fbstree_otherlev[, fbsID2 :=paste0("S",fbsID2)] fbstree_otherlev[, fbsID3 :=paste0("S",fbsID3)] fbs_other_level<-merge( fbs_balanced_bis[measuredElementSuaFbs %in% c("5023","5166")], fbstree_otherlev, by=c("measuredItemFbsSua"), all.x = TRUE ) # aggregate(fbs_other_level, by =list(p$yearVar,p$geoVar,p$elementVar, "fbsID3"), FUN=sum(Value)) level_3 <- aggregate( Value ~ geographicAreaM49+fbsID3 +timePointYears + measuredElementSuaFbs, fbs_other_level, sum, na.rm = TRUE) setnames(level_3,"fbsID3","measuredItemFbsSua") level_2 <- aggregate( Value ~ geographicAreaM49+fbsID2 +timePointYears + measuredElementSuaFbs, fbs_other_level, sum, na.rm = TRUE) setnames(level_2,"fbsID2","measuredItemFbsSua") # level_1 <- aggregate( # Value ~ geographicAreaM49+fbsID1 +timePointYears + measuredElementSuaFbs, # fbs_other_level, sum, na.rm = TRUE) # setnames(level_1,"fbsID1","measuredItemFbsSua") data_level<-rbind(level_3,level_2) setDT(data_level) data_level[,flagObservationStatus:="I"] data_level[,flagMethod:="s"] data_level<-data_level[,names(fbs_balanced_bis),with=FALSE] #christian issue fbs_balanced_bis<-rbind( fbs_balanced_bis[!data_level, on=c("geographicAreaM49","timePointYears","measuredItemFbsSua","measuredElementSuaFbs")], data_level ) #ADD food supply (Grams/capita/day) in FBS balanced foodGram_data_fb <- dt_left_join( # Food fbs_balanced_bis[ measuredElementSuaFbs == '5141', list( geographicAreaM49, measuredItemFbsSua, measuredElementSuaFbs, timePointYears, food = Value, flagObservationStatus = "T", flagMethod = "i" ) ], # Population popSWS[, list(geographicAreaM49, timePointYears, population = Value)], by = c('geographicAreaM49', 'timePointYears') ) foodGram_data_fb[,Value:=(food*1000000)/(365*population*1000)] foodGram_data_fb[,measuredElementSuaFbs:="665"] foodGram_data_fb[, c("food", "population") := NULL] foodGram_data_fb<-foodGram_data_fb[,list(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears,Value,flagObservationStatus,flagMethod)] fbs_balanced_bis<-rbind(fbs_balanced_bis,foodGram_data_fb) # aggregate( # measuredItemSuaFbs ~ geographicAreaM49+measuredItemFbsSua+timePointYears, # Item_with_unbalanced, paste0, collapse = "; ") message("saving FBS balanced...") SaveData(domain = "suafbs", dataset = "fbs_balanced_", data = fbs_balanced_bis, waitTimeout = 20000) SaveData(domain = "suafbs", dataset = "fbs_balanced_", data = popData, waitTimeout = 20000) popData[,measuredItemFbsSua:="S2901"] SaveData(domain = "suafbs", dataset = "fbs_balanced_", data = popData, waitTimeout = 20000) #end fbs balanced--------------------------------------- ###################### # data_residual<-copy(data) # setnames(data_residual,"measuredItemSuaFbs" ,"measuredItemFbsSua") # calculateImbalance(data=data_residual,keep_supply = FALSE,keep_utilizations = FALSE) # # data_residual[,`:=`(Value=imbalance, # measuredElementSuaFbs="residual", # imbalance=NULL)] # # setnames(data_residual,"measuredItemFbsSua","measuredItemSuaFbs") # # data_residual<-unique(data_residual, by=colnames(data)) # # data<-rbind(data[measuredElementSuaFbs %!in% c("residual")],data_residual) Item_with_unbalanced<- data[measuredElementSuaFbs=="residual"][, balanced:=ifelse(abs(Value)<1000,TRUE,FALSE)][balanced==FALSE] Item_with_unbalanced<-merge( Item_with_unbalanced, fbsTree, by=c(p$itemVar), allow.cartesian = TRUE, all.x = TRUE ) Item_with_unbalanced<-Item_with_unbalanced[!is.na(fbsID4) & (measuredItemSuaFbs %!in% onlyCalories), list(geographicAreaM49,timePointYears, measuredItemFbsSua=paste0("S",fbsID4), measuredItemSuaFbs) ] Item_with_unbalanced<-unique(Item_with_unbalanced,by=c(colnames(Item_with_unbalanced))) if (nrow(Item_with_unbalanced) > 0) { Item_with_unbalanced<-aggregate( measuredItemSuaFbs ~ geographicAreaM49+measuredItemFbsSua+timePointYears, Item_with_unbalanced, paste0, collapse = "; ") setDT(Item_with_unbalanced) } else { Item_with_unbalanced <- data.table( geographicAreaM49 = character(), measuredItemFbsSua = character(), timePointYears = character(), measuredItemSuaFbs = character() ) } # # check if the primary or proxy primary is balanced primProxiPrim<-unique(Utilization_Table[primary_item=="X" | proxy_primary=="X",get("cpc_code")]) balanceSUA<-data[measuredItemSuaFbs %in% primProxiPrim & measuredElementSuaFbs=="residual"] balanceSUA<-balanceSUA[measuredItemSuaFbs %!in% onlyCalories] balanceSUA[,balanced:=ifelse(abs(Value)<1000,TRUE,FALSE)] balanceSUA<-balanceSUA[, list(geographicAreaM49,timePointYears,measuredItemSuaFbs,balanced)] balanceSUA<-merge( balanceSUA, fbsTree, by=c(p$itemVar), allow.cartesian = TRUE, all= TRUE ) balanceSUA<-balanceSUA[,list(geographicAreaM49,timePointYears,parent=measuredItemSuaFbs, balanced,measuredItemFbsSua=fbsID4)] balanceSUA<-unique(balanceSUA,by=c(names(balanceSUA))) balanceSUA[,measuredItemFbsSua:=paste0("S",measuredItemFbsSua)] ### File containing imbalances greater that 1 MT---------------------- # fbs_residual_to_send<-fbs_residual[abs(imbalance_percentage)>=1] fbs_residual_to_send<-copy(fbs_balanced_bis[measuredElementSuaFbs=="5166" & abs(Value)>1000]) fbs_residual_to_send<-merge( fbs_residual_to_send, fbs_residual[,list(geographicAreaM49,timePointYears,measuredItemFbsSua,supply)], by=c(p$geoVar,p$yearVar,"measuredItemFbsSua"), all.x =TRUE ) fbs_residual_to_send[,imbalance_percentage:=round((Value/supply)*100,0), by=c(p$geoVar,p$yearVar,"measuredItemFbsSua") ] fbs_residual_to_send<-merge( fbs_residual_to_send, balanceSUA, by=c(p$geoVar,p$yearVar,"measuredItemFbsSua"), allow.cartesian = TRUE, all.x =TRUE ) fbs_residual_to_send<-merge( fbs_residual_to_send, Item_with_unbalanced, by=c(p$geoVar,p$yearVar,"measuredItemFbsSua"), allow.cartesian = TRUE, all = TRUE ) # fbs_residual_to_send<-fbs_residual_to_send[abs(imbalance)>=1000 | !is.na(measuredItemSuaFbs)] # fbs_residual_to_send[,unbalanced:=ifelse(balanced==FALSE & abs(imbalance)>1000,TRUE,FALSE)] # fbs_residual_to_send[balanced==FALSE & abs(imbalance)<1000,unbalanced:=NA] fbs_residual_to_send[,balanced:=NULL] if (nrow(fbs_residual_to_send) > 9) { fbs_residual_to_send<-nameData("suafbs", "fbs_balanced_", fbs_residual_to_send) } LabelItem<-unique( data[,list(measuredItemFbsSua=measuredItemSuaFbs)],by=c("measuredItemFbsSua") ) LabelItem<-nameData("suafbs", "fbs_balanced_", LabelItem) standQTY<-merge( standQTY, LabelItem[,list(measuredItemChildCPC=measuredItemFbsSua, measuredItemChildCPC_name=measuredItemFbsSua_description)], by=c("measuredItemChildCPC") ) standQTY<-merge( standQTY, LabelItem[,list(measuredItemParentCPC=measuredItemFbsSua, measuredItemParentCPC_name=measuredItemFbsSua_description)], by=c("measuredItemParentCPC") ) standQTY<-merge( standQTY, fbsTree[,list(measuredItemParentCPC=measuredItemSuaFbs, FBS_group=fbsID4)] ) # extracting the dataset contains items of the commodity tree that are standardized outside the #FBS group: this will be merged in the summary file containing FBS imbalances Items_outside_tree<-standQTY[measuredElementSuaFbs=="foodManufacturing" & Value>0, list(geographicAreaM49,timePointYears,Child_outside_tree=measuredItemChildCPC, measuredItemFbsSua=paste0("S",FBS_group))] Items_outside_tree<-aggregate( Child_outside_tree ~measuredItemFbsSua+ geographicAreaM49+timePointYears, Items_outside_tree, paste0, collapse = "; ") fbs_residual_to_send<-merge( fbs_residual_to_send, Items_outside_tree, by=c("geographicAreaM49","timePointYears","measuredItemFbsSua"), all.x = TRUE ) #Consider only fbsID4 groups for the final summary file fbsID4_groups<-paste0("S",unique(fbsTree$fbsID4)) #fbs_residual_to_send<-fbs_residual_to_send[measuredItemFbsSua %in% fbsID4_groups] #----- standQTY<-standQTY[,list(FBS_group,geographicAreaM49,timePointYears,measuredElementSuaFbs, measuredItemParentCPC,measuredItemParentCPC_name, measuredItemChildCPC,measuredItemChildCPC_name,Value, flagObservationStatus,flagMethod,extractionRate,share,weight, standard_child,Stand_Value)] #if the number of SUAs is more than 1 we cannot include COUNTRY_NAME, in the file name if(length(selectedGEOCode)==1){ tmp_file_residual<- tempfile(pattern = paste0("FBS_IMBALANCES_", COUNTRY_NAME, "_"), fileext = '.csv') tmp_file_standData<- tempfile(pattern = paste0("Stand_SUA_", COUNTRY_NAME, "_"), fileext = '.csv') }else{ tmp_file_residual<- tempfile(pattern = paste0("FBS_IMBALANCES_"), fileext = '.csv') tmp_file_standData<- tempfile(pattern = paste0("Stand_SUA_"), fileext = '.csv') } fbs_residual_to_send<-unique(fbs_residual_to_send, by=c(names(fbs_residual_to_send))) write.csv(fbs_residual_to_send, tmp_file_residual) write.csv(standQTY, tmp_file_standData) ### End File containing imbalances greater that 1 MT---------------------- #File containing aggregated DES from FBS----------------------- fbs_des_to_send<-fbs_balanced[measuredElementSuaFbs=="664"] fbs_des_to_send<-nameData("suafbs", "fbs_balanced_", fbs_des_to_send) fbs_des_to_send <- dcast( fbs_des_to_send, geographicAreaM49_description + measuredElementSuaFbs_description+measuredItemFbsSua_description ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) #if the number of SUAs is more than 1 we cannot include COUNTRY_NAME, in the file name if(length(selectedGEOCode)==1){ tmp_file_des<- tempfile(pattern = paste0("FBS_DES_", COUNTRY_NAME, "_"), fileext = '.csv') }else{ tmp_file_des<- tempfile(pattern = paste0("FBS_DES_"), fileext = '.csv') } write.csv(fbs_des_to_send, tmp_file_des) #End File containing aggregated DES from FBS----------------------- #DES comparison: SUA and FBS----------------- DEssua<-dataDes[measuredElementSuaFbs=="calories",] DEssua<-DEssua[, list(Value=sum(Value,na.rm = TRUE)), by=c("geographicAreaM49","measuredElementSuaFbs","timePointYears") ] DEssua<-nameData("suafbs", "sua_balanced", DEssua) DEssua[,measuredItemFbsSua_description:="DES from SUA_bal"] DEssua <- dcast( DEssua, geographicAreaM49_description + measuredElementSuaFbs_description+measuredItemFbsSua_description ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) setDT(DEssua) DEssua[,`measuredElementSuaFbs_description`:="Food supply (/capita/day) [kcal]"] setDT(fbs_des_to_send) DesFBS<-fbs_des_to_send[measuredItemFbsSua_description=="GRAND TOTAL - DEMAND"] DesFBS[,measuredItemFbsSua_description:="DES from FBS"] ComparativeDES<-rbind(DEssua,DesFBS) #if the number of SUAs is more than 1 we cannot include COUNTRY_NAME, in the file name if(length(selectedGEOCode)==1){ tmp_file_desSuaFbs<- tempfile(pattern = paste0("DES_SUA_vs_FBS_", COUNTRY_NAME, "_"), fileext = '.csv') }else{ tmp_file_desSuaFbs<- tempfile(pattern = paste0("DES_SUA_vs_FBS_"), fileext = '.csv') } write.csv(ComparativeDES, tmp_file_desSuaFbs) #End DES comparison: SUA and FBS----------------- #Items with DES and without FBS group---------------------- DESItems_noFBSGroup<-dataDes[measuredItemSuaFbs %!in% fbsTree[,get(p$itemVar)] & Value>0,] DESItems_noFBSGroup[,measuredElementSuaFbs:="664"] DESItems_noFBSGroup<-nameData("suafbs", "sua_balanced", DESItems_noFBSGroup) if(nrow(DESItems_noFBSGroup)>0){ DESItems_noFBSGroup <- dcast( DESItems_noFBSGroup, geographicAreaM49_description + measuredElementSuaFbs_description+measuredItemSuaFbs ~ timePointYears, fun.aggregate = sum, value.var = "Value" ) } #if the number of SUAs is more than 1 we cannot include COUNTRY_NAME, in the file name if(length(selectedGEOCode)==1){ tmp_file_noFbsGroup<- tempfile(pattern = paste0("ITEMS_NO_FBSGROUP_", COUNTRY_NAME, "_"), fileext = '.csv') }else{ tmp_file_noFbsGroup<- tempfile(pattern = paste0("ITEMS_NO_FBSGROUP_"), fileext = '.csv') } write.csv(DESItems_noFBSGroup, tmp_file_noFbsGroup) #End Items with DES and without FBS group---------------------- fin<-Sys.time() duree<-fin-commence if (!CheckDebug()) { send_mail( from = "<EMAIL>", to = swsContext.userEmail, subject = "Results from newBalancing plugin", body = c("If all commodities of a tree (FBS item) are balanced at SUA level, then the FBS item is balanced by moving eventual residual to process.", tmp_file_des, tmp_file_residual, tmp_file_noFbsGroup, tmp_file_desSuaFbs, tmp_file_nonStandItemps #, #tmp_file_standData ) ) } print("Done! Please, check you email") <file_sep>/R/faoswsStandardization-package.R #' Package for standardization of Food Balance Sheets #' #' This package contains support functions for the standardization process. The process contains balancing as well (contained in the faoswsBalancing package). The main function \code{standardizationWrapper} controls the flow of the whole process. #' #' @docType package #' @name faoswsStandardization-package #' @aliases faoswsStandardization #' @author <NAME> <<EMAIL>> #' #' @import data.table NULL <file_sep>/R/collapseEdges.R ##' Collapse Edges ##' ##' This function takes a "edge" data.table (i.e. a data.table with parent/child ##' columns and an extraction rate column) and condenses the parent/child ##' relationships. For example, wheat may be processed into flour which is in ##' turn processed into bread. Thus, we can standardize bread to flour and then ##' the wheat, but it'd be easier to just standardize straight to bread. This ##' function condenses the edges by multiplying the extraction rates so that you ##' can take bread straight to wheat. ##' ##' @param edges A data.table containing three columns (corresponding to a ##' parent, a child, and an extraction rate). ##' @param parentName The column name of the parent column in edges. ##' @param childName The column name of the child column in edges. ##' @param extractionName The column name of the extraction rate column in ##' edges. ##' @param keyCols The column name(s) of the columns of edges which should be ##' considered as keys. These columns will thus be included in any joins to ##' ensure we don't get duplicates. If there is no key, this can be "". ##' ##' @return A data.table of the same structure as edges, but with intermediate ##' steps removed. ##' collapseEdges = function(edges, parentName = "parentID", childName = "childID", extractionName = "extractionRate", keyCols = c("timePointYearsSP", "geographicAreaFS")){ ## Data quality checks stopifnot(is(edges, "data.table")) stopifnot(c(parentName, childName, extractionName) %in% colnames(edges)) if(max(edges[[extractionName]][edges[[extractionName]] < Inf]) > 100) stop("Extraction rates larger than 100 indicate they are probably ", "expressed in different units than on [0,1]. This will cause ", "huge problems when multiplying, and should be fixed.") ## Test for loops findProcessingLevel(edgeData = edges, from = parentName, to = childName) targetNodes = setdiff(edges[[parentName]], edges[[childName]]) edgesCopy = copy(edges[, c(parentName, childName, extractionName, keyCols), with = FALSE]) ################## edgesCopy2 = copy(edges[, c(parentName, childName, extractionName, keyCols,"weight"), with = FALSE]) edgesCopy2 = edgesCopy2[,c("measuredItemChildCPC","weight"),with=FALSE] setnames(edgesCopy2,"measuredItemChildCPC","measuredItemParentCPC") edgesCopy3=data.table(left_join(edgesCopy,edgesCopy2,by="measuredItemParentCPC")) edge2remove=edgesCopy3[(weight==0&grepl("f???_",measuredItemChildCPC)),c("measuredItemParentCPC","measuredItemChildCPC"), with=FALSE] edges=edges[!edge2remove,,on=c("measuredItemParentCPC","measuredItemChildCPC")] edgesCopy=copy(edgesCopy3[!(weight==0&grepl("f???_",measuredItemChildCPC))]) edgesCopy[,weight:=NULL] ################ setnames(edgesCopy, c(parentName, childName, extractionName), c("newParent", parentName, "extractionMult")) finalEdges = edges[get(parentName) %in% targetNodes, ] currEdges = edges[!get(parentName) %in% targetNodes, ] while(nrow(currEdges) > 0){ currEdges = merge(currEdges, edgesCopy, by = c(parentName, keyCols), all.x = TRUE, allow.cartesian = TRUE) ## Update edges table with new parents/extraction rates. For edges that ## didn't get changed, we keep the old parent name and extraction rate. currEdges[, c(parentName) := ifelse(is.na(newParent), get(parentName), newParent)] currEdges[, c(extractionName) := get(extractionName) * ifelse(is.na(extractionMult), 1, extractionMult)] currEdges[, c("newParent", "extractionMult") := NULL] finalEdges = rbind(finalEdges, currEdges[get(parentName) %in% targetNodes, ]) currEdges = currEdges[!get(parentName) %in% targetNodes, ] } finalEdges = unique(finalEdges,by=colnames(finalEdges)) return(finalEdges) } <file_sep>/R/getCommodityTreeNewMethod.R ##' Get Commodity Tree ##' ##' This function pulls the commodity trees in the new CPC system. ##' ##' @param geographicAreaM49 A character vector of area codes. The trees ##' returned are specific to country and year; thus, providing this parameter ##' limits which trees are pulled. If NULL, all are used. ##' @param timePointYears A character vector of years. See geographicAreaM49. ##' ##' @return A data.table object containing the commodity tree. The dimension ##' columns correspond to the country, year, parent, and child commodity. Two ##' value columns are available: extraction rate and share. The logic of the ##' NEW system is that 0 ExtractionRates are NA, meaning that that connection ##' is not valid for that cpuntry/commodity/year combination ##' ##' @export ##' getCommodityTreeNewMethod = function(geographicAreaM49 = NULL, timePointYears = NULL){ ## Data Quality Checks if(!exists("swsContext.datasets")){ stop("No swsContext.datasets object defined. Thus, you probably ", "won't be able to read from the SWS and so this function won't ", "work.") } stopifnot(is(geographicAreaM49, "character")) stopifnot(is(timePointYears, "character")) ## Define constants treeelemKeys = c("5423", "5431") # 5423 = Extraction Rate [hg/t] # 5431 = Share of utilization [%] ## Define the dimensions and check for input errors allAreaCodes = GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", dimension = "geographicAreaM49") allAreaCodes = allAreaCodes[type == "country", code] allYears = GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", dimension = "timePointYears")[, code] if(!is.null(geographicAreaM49)){ stopifnot(geographicAreaM49 %in% allAreaCodes) }else{ geographicAreaM49=allAreaCodes } if(!is.null(timePointYears)){ stopifnot(timePointYears %in% allYears) }else{ timePointYears=allYears } treeitemPKeys = GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemParentCPC_tree") treeitemPKeys = treeitemPKeys[, code] treeitemCKeys = GetCodeList(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", "measuredItemChildCPC_tree") treeitemCKeys = treeitemCKeys[, code] treekey = faosws::DatasetKey(domain = "suafbs", dataset = "ess_fbs_commodity_tree2", dimensions = list( geographicAreaM49 = Dimension(name = "geographicAreaM49", keys = geographicAreaM49), measuredElementSuaFbs = Dimension(name = "measuredElementSuaFbs", keys = treeelemKeys), measuredItemParentCPC = Dimension(name = "measuredItemParentCPC_tree", keys = treeitemPKeys), measuredItemChildCPC = Dimension(name = "measuredItemChildCPC_tree", keys = treeitemCKeys), timePointYears = Dimension(name = "timePointYears", keys = timePointYears) )) ## Extract the specific tree tree = faosws::GetData(treekey,omitna = FALSE) if("flag_obs_status_v2"%in%colnames(tree)){ setnames(tree,"flag_obs_status_v2","flagObservationStatus") } if(nrow(tree[measuredElementSuaFbs=="5423"&is.na(Value)])>0){ tree[measuredElementSuaFbs=="5423"&is.na(Value),flagObservationStatus:="T"] tree[measuredElementSuaFbs=="5423"&is.na(Value),flagMethod:="-"] tree[measuredElementSuaFbs=="5423"&is.na(Value),Value:=0] } if(nrow(tree[measuredElementSuaFbs=="5431"&is.na(Value)])>0){ tree[measuredElementSuaFbs=="5431"&is.na(Value),flagObservationStatus:="E"] tree[measuredElementSuaFbs=="5431"&is.na(Value),flagMethod:="-"] tree[measuredElementSuaFbs=="5431"&is.na(Value),Value:=0] } tree[measuredElementSuaFbs=="5423",measuredElementSuaFbs:="extractionRate"] tree[measuredElementSuaFbs=="5431",measuredElementSuaFbs:="share"] message("Commodity Tree correctly downloaded") setnames(tree,c("measuredItemParentCPC_tree","measuredItemChildCPC_tree"), c("measuredItemParentCPC","measuredItemChildCPC")) return(tree) }<file_sep>/R/convertSugarCodes_new.R ##' Converts sugar codes 23511.01 and 23512 to 2351f ##' ##' ##' This function harmonize sugar codes. ##' Raw cane and beet sugar are considered as separate codes in some domain, like trade, because sugar raw can be traded ##' as beet raw, cane raw or just raw (23511.01, 23512 or 2351f), ##' but when one has to go from the processed product to the primary product, ##' is not possible to know if a code 2351f has to be standardized to cane or beet, therefore ##' in the standardization process cane and beet have to be considered as a unique code (2351f) ##' This function makes checks and harmonize sugar codes ##' ##' ##' @param data the downloaded data from sua ##' @return A data.table with the data fixed for sugar ##' @export ##' convertSugarCodes_new <- function(data) { d <- copy(data) # Keep name as it can be measuredItemFbsSua or measuredItemFbsSua (why????) item_name <- names(d)[grepl("Item", names(d))] setnames(d, item_name, "item") sugar <- d[item %in% c('23511.01', '23512', '2351f')] sugar <- sugar[order(geographicAreaM49, measuredElementSuaFbs, timePointYears, -item)] stock_elem_lab <- unique(d$measuredElementSuaFbs)[grep("5071|stock_change|stockChange", unique(d$measuredElementSuaFbs))] if (length(stock_elem_lab) > 0) { sugar_stock <- sugar[measuredElementSuaFbs == stock_elem_lab] sugar <- sugar[measuredElementSuaFbs != stock_elem_lab] } else { sugar_stock <- d[0] } if ("residual" %in% sugar$measuredElementSuaFbs) { sugar_resid <- sugar[measuredElementSuaFbs == "residual"] sugar <- sugar[measuredElementSuaFbs != "residual"] } else { sugar_resid <- d[0] } if (nrow(sugar) == 0) { return(d) } sugar[, n := .N, by = c('geographicAreaM49', 'measuredElementSuaFbs', 'timePointYears') ] sugar[, Value_max := max(Value[item == "2351f"], sum(Value[item %in% c('23511.01', '23512')])), by = c('geographicAreaM49', 'measuredElementSuaFbs', 'timePointYears') ] data("flagWeightTable", package = "faoswsFlag") sugar[ n > 0, `:=`( flag_obs = ifelse( "2351f" %in% item[Value == Value_max], flagObservationStatus[Value == Value_max], faoswsFlag::aggregateObservationFlag(flagObservationStatus[item != "2351f"]) ), flag_meth = ifelse( "2351f" %in% item[Value == Value_max], flagMethod[Value == Value_max], ifelse(all(c('23511.01', '23512') %in% item), 's', flagMethod[item != "2351f"]) ) ), by = c('geographicAreaM49', 'measuredElementSuaFbs', 'timePointYears') ] sugar_summ <- sugar[, .( Value = max(Value[item == "2351f"], sum(Value[item %in% c('23511.01', '23512')])), flagObservationStatus = unique(flag_obs), flagMethod = unique(flag_meth), item = '2351f' ), by = c('geographicAreaM49', 'measuredElementSuaFbs', 'timePointYears') ] res <- rbind( d[!(item %in% c('23511.01', '23512', '2351f'))], sugar_summ, sugar_stock, sugar_resid ) setnames(res, "item", item_name) return(res) } <file_sep>/R/checkShareValue.R ##' Check if values of shares are consistent and substitute inconsistent values ##' ##' This function checks between a subset of the Tree having official shares ##' but with the sum not equal to 1. ##' It checks where is the problem and correct it ##' The structure of this function is articulated on purpose ##' for sake of clarity ##' ##' @param One single subset of the Tree, which means, a subset having all the parent of a single child ##' where the child is an official one. The subset has the characteristis of having shares not summing at 1 ##' ##' @return The function returns the subTree with the corrected shares and ##' with a severity index to be saved back in order to have a different color also where there ##' are shares that have been changed ##' ##' @export checkShareValue=function(tree2Subset){ # Check and count cases # Number of rows linesT=nrow(tree2Subset) ######################## #### Number of PROTECTED Pt=tree2Subset[checkFlags=="(E,f)"] nPt=nrow(tree2Subset[checkFlags=="(E,f)"]) ############## # Number of PROTECTED + MISSING PtM=tree2Subset[checkFlags=="(E,f)"&is.na(share)] nPtM=nrow(tree2Subset[checkFlags=="(E,f)"&is.na(share)]) ############## # Number of PROTECTED + NoMISSING PtnoM=tree2Subset[checkFlags=="(E,f)"&!(is.na(share))] nPtnoM=nrow(tree2Subset[checkFlags=="(E,f)"&!(is.na(share))]) ############## # Number of PROTECTED + NegAvailabilities PtnegAv=tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))] nPtnegAv=nrow(tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))]) ############## # Number of PROTECTED + PosAvailabilities PtposAv=tree2Subset[checkFlags=="(E,f)"&availability.child>0] nPtposAv=nrow(tree2Subset[checkFlags=="(E,f)"&availability.child>0]) ######################## # Number of PROTECTED + MISSING + NegAvailability PtMnegAv=tree2Subset[checkFlags=="(E,f)"&is.na(share)&(availability.child<=0|is.na(availability.child))] nPtMnegAv=nrow(tree2Subset[checkFlags=="(E,f)"&is.na(share)&(availability.child<=0|is.na(availability.child))]) # Number of PROTECTED + MISSING + PosAvailability PtMposAv=tree2Subset[checkFlags=="(E,f)"&is.na(share)&availability.child>0] nPtMposAv=nrow(tree2Subset[checkFlags=="(E,f)"&is.na(share)&availability.child>0]) # Number of PROTECTED + noMISSING + NegAvailability PtnoMnegAv=tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&(availability.child<=0|is.na(availability.child))] nPtnoMnegAv=nrow(tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&(availability.child<=0|is.na(availability.child))]) # Number of PROTECTED + noMISSING + PosAvailability PtnoMposAv=tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&availability.child>0] nPtnoMposAv=nrow(tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&availability.child>0]) ######################## ######################## #### Number of NOT Protected numNoProt=nrow(tree2Subset[checkFlags!="(E,f)"]) # Number of No PROTECTED + NegAvailability (doesn't matter if NA) NoPtnegAv=tree2Subset[checkFlags!="(E,f)"&(availability.child<=0|is.na(availability.child))] nNoPtnegAv=nrow(tree2Subset[checkFlags!="(E,f)"&(availability.child<=0|is.na(availability.child))]) # Number of No PROTECTED + PosAvailability (doesn't matter if NA) NoPtposAv=tree2Subset[checkFlags!="(E,f)"&availability.child>0] nNoPtposAv=nrow(tree2Subset[checkFlags!="(E,f)"&availability.child>0]) ######################## ############################################################ ################# defining alternatives ################# ############################################################ if(linesT==1){ ##################### 1. ##################### # 1. linesT=1 (Extraction Rate is never NA) if(nPtM==1){ ###################### 1.A share = NA if(nPtMnegAv==1){ # 1.A.a Yes Negative Availability case="1.A.a" }else{ # 1.A.b No Negative Availability case="1.A.b" } }else{# end of 1.A ###################### 1.B share != NA if(nPtnoMnegAv>0){ # 1.B.a Yes Negative Availability case="1.B.a" }else{ # 1.B.b No Negative Availability case="1.B.b" } } }else{# END of 1 ##################### 2. ##################### # linesT>1 (Extraction Rate is never NA) if(linesT==nPt){ # 2.A. All protected line if(nPtnoM==nPt){ ##################### 2.A.a share != NA if(nPtnoM==nPtnoMposAv){ # 2.A.a.1 No Neg Availability case="2.A.a.1" }else{ # 2.A.a.2 Yes Negative Availability case="2.A.a.2" } }else{ # 2.A.b some share == NA if(nPtnegAv==0){ # 2.A.b.1 No Neg Availability case="2.A.b.1" }else{ # 2.A.b.2 Yes Negative Availability case="2.A.b.2" } } }else{ # END of 2.A ###################### 2.B. NOT All protected line ########################################################## if(nNoPtnegAv==0){ ########## 2.B.a. No neg Av in No Protected if(nPtnegAv==0){ # 2.B.a.1. No neg Av in Protected if(nPtM==0){ # 2.B.a.1.i. No Missing case="2.B.a.1.i" }else{ # 2.B.a.1.ii.Yes Missing case="2.B.a.1.ii" } }else{ # 2.B.a.2. Yes neg Av in Protected if(nPtM==0){ # 2.B.a.2.i. No Missing case="2.B.a.2.i" }else{ # 2.B.a.2.ii.Yes Missing case="2.B.a.2.ii" } } }else{ ########## 2.B.b. Yes neg Av in No Protected if(nPtnegAv==0){ # 2.B.b.1. No neg Av in Protected if(nPtMposAv==0){ # 2.B.b.1.i. No Missing case="2.B.b.1.i" }else{ # 2.B.b.1.ii. Yes Missing case="2.B.b.1.ii" } }else{ # 2.B.b.2. Yes neg Av in Protected if(nPtM==0){ # 2.B.b.2.i.No Missing case="2.B.b.2.i" }else{ # 2.B.b.2.ii.YES Missing case="2.B.b.2.ii" } } } } } ############################################################ ######## Define function for Alternative cases ######## ############################################################ ############ fun1 # 1. linesT=1 # (protected line) # A. Yes Missing # a. Yes Negative Availability fun1=function(tree2Subset,case="1.A.a"){ tree2Subset[,newShare:=1] tree2Subset[,severity:=3] tree2Subset[,message:="NA Shares, Neg Avail, share changet to 1"] return(tree2Subset) } ############ fun2 # 1. linesT=1 # (protected line) # A. Yes Missing # b. No Negative Availability fun2=function(tree2Subset,case="1.A.b"){ tree2Subset[,newShare:=1] tree2Subset[,severity:=3] tree2Subset[,message:="NA Shares, share changet to 1"] return(tree2Subset) } ############ fun3 # 1. linesT=1 # (protected line) # B. share != NA # a. Yes Negative Availability fun3=function(tree2Subset,case="1.B.a"){ tree2Subset[,newShare:=1] tree2Subset[,severity:=3] tree2Subset[,message:="Share !=1, Neg Avail, share changet to 1"] return(tree2Subset) } ############ fun4 # 1. linesT=1 # (protected line) # B. No Missing # b. No Negative Availability fun4=function(tree2Subset,case="1.B.b"){ tree2Subset[,newShare:=1] tree2Subset[,severity:=3] tree2Subset[,message:="Share !=1,share changet to 1"] return(tree2Subset) } ############ fun5 # 2. linesT>1 # A. All protected line # a. No Missing # 1. No Neg Availability fun5=function(tree2Subset,case="2.A.a.1"){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] tree2Subset[,severity:=2] tree2Subset[,message:="all prot, sum!=0, all recalculated"] return(tree2Subset) } ############ fun6 # 2. linesT>1 # A. All protected line # a. No Missing # 2. Yes Negative Availability # In this case recalculate shares and give alert for negativa availablity # but do nothing about it, as the shares are protected fun6=function(tree2Subset,case="2.A.a.2"){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[(availability.child<=0|is.na(availability.child)),severity:=3] tree2Subset[(availability.child<=0|is.na(availability.child)),message:="all prot, neg avail, sum!=0, all recalculated"] tree2Subset[availability.child>0,severity:=2] tree2Subset[availability.child>0,message:="all prot, sum!=0, all recalculated"] return(tree2Subset) } ############ fun7 # 2. linesT>1 # A. All protected line # b. Yes Missing # 1. No Neg Availability # In this case recalculate all shares and give alert for missing shares fun7=function(tree2Subset,case="2.A.b.1"){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] tree2Subset[is.na(share),severity:=3] tree2Subset[is.na(share),message:="all protected, missing share, sum!=0, recalculated"] tree2Subset[!is.na(share),severity:=2] tree2Subset[!is.na(share),message:="all protected, sum!=0, missing shares, recalculated"] return(tree2Subset) } ############ fun8 # 2. linesT>1 # A. All protected line # b. Yes Missing # 2. Yes Negative Availability # This is as the previous, only messages changes fun8=function(tree2Subset,case="2.A.b.2"){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] # if negative availability is on NA share freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[, sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[is.na(share)&availability.child>0,severity:=2] tree2Subset[is.na(share)&(availability.child<=0|is.na(availability.child)),severity:=3] tree2Subset[is.na(share)&availability.child>0,message:="all prot, missing share, sum!=0, recalculated"] tree2Subset[is.na(share)&(availability.child<=0|is.na(availability.child)),message:="all prot, missing share, neg Avail, sum!=0, recalculated"] tree2Subset[!(is.na(share))&availability.child>0,severity:=2] tree2Subset[!(is.na(share))&(availability.child<=0|is.na(availability.child)),severity:=2] tree2Subset[!(is.na(share))&availability.child>0,message:="all prot, sum!=0, recalculated"] tree2Subset[!(is.na(share))&(availability.child<=0|is.na(availability.child)),message:="all prot, sum!=0, neg Avail, recalculated"] return(tree2Subset) } ############ fun9 # 2. linesT>1 # B. NOT All protected line # a. No neg Av in No Protected # 1. No neg Av in Protected # i. No Missing fun9=function(tree2Subset,case="2.B.a.1.i"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share)] # there is a difference if the sum of protected is >1 if(shareProt>1){ # in this case recalculate all tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] tree2Subset[checkFlags=="(E,f)",severity:=3] tree2Subset[checkFlags=="(E,f)",message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] tree2Subset[checkFlags!="(E,f)",severity:=as.integer(1)] tree2Subset[checkFlags!="(E,f)",message:="only not prot shares recalculated"] tree2Subset[checkFlags=="(E,f)",severity:=as.integer(0)] tree2Subset[checkFlags=="(E,f)",message:="prot share"] } return(tree2Subset) } ############ fun10 # 2. linesT>1 # B. NOT All protected line # a. No neg Av in No Protected # 1. No neg Av in Protected # ii. Yes Missing fun10=function(tree2Subset,case="2.B.a.1.ii"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share,na.rm=T)] if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] tree2Subset[checkFlags=="(E,f)",severity:=3] tree2Subset[checkFlags=="(E,f)",message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] tree2Subset[checkFlags=="(E,f)"&!(is.na(share)),severity:=0] tree2Subset[checkFlags=="(E,f)"&!(is.na(share)),message:="valid prot share"] tree2Subset[checkFlags=="(E,f)"&is.na(share),severity:=3] tree2Subset[checkFlags=="(E,f)"&is.na(share),message:="Missing prot share recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] } return(tree2Subset) } ############ fun11 # 2. linesT>1 # B. NOT All protected line # a. No neg Av in No Protected # 2. Yes neg Av in Protected # i. No Missing fun11=function(tree2Subset,case="2.B.a.2.i"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share)] # there is a difference if the sum of protected is >1 if(shareProt>1){ # in this case recalculate all tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[, sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[, newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)",severity:=3] tree2Subset[checkFlags=="(E,f)",message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),message:="sum of prot shares>1 & neg avail, recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0,severity:=3] tree2Subset[checkFlags=="(E,f)"&availability.child>0,message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] tree2Subset[checkFlags!="(E,f)",severity:=as.integer(1)] tree2Subset[checkFlags!="(E,f)",message:="only not prot shares recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),severity:=as.integer(1)] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),message:="prot share, neg avail"] tree2Subset[checkFlags=="(E,f)"&availability.child>0,severity:=as.integer(0)] tree2Subset[checkFlags=="(E,f)"&availability.child>0,message:="prot share"] } return(tree2Subset) } ############ fun12 # 2. linesT>1 # B. NOT All protected line # a. No neg Av in No Protected # 2. Yes neg Av in Protected # ii. Yes Missing fun12=function(tree2Subset,case="2.B.a.2.ii"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share,na.rm=T)] if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),message:="sum of prot shares>1, neg avail, missing Share, recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),severity:=2] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),message:="sum of prot shares>1, neg avail, recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0&is.na(share),severity:=3] tree2Subset[checkFlags=="(E,f)"&availability.child>0&is.na(share),message:="sum of prot shares>1, missing share, recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0&!(is.na(share)),severity:=2] tree2Subset[checkFlags=="(E,f)"&availability.child>0&!(is.na(share)),message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare:=round(availability.child/sum(availability.child,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[(checkFlags=="(E,f)")|(is.na(share)), negShare:=1/freq] tree2Subset[(checkFlags=="(E,f)")|(is.na(share)), sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[(checkFlags=="(E,f)")|(is.na(share)), tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[(checkFlags=="(E,f)")|(is.na(share)), newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare-shareProt*(negShare), (tempAvailability / sum(tempAvailability, na.rm = TRUE)))-shareProt*(tempAvailability / sum(tempAvailability, na.rm = TRUE))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&(availability.child<=0|is.na(availability.child)),severity:=1] tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&(availability.child<=0|is.na(availability.child)),message:="valid prot share, neg avail"] tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&availability.child>0,severity:=0] tree2Subset[checkFlags=="(E,f)"&!(is.na(share))&availability.child>0,message:="valid prot share"] tree2Subset[checkFlags=="(E,f)"&is.na(share)&(availability.child<=0|is.na(availability.child)),severity:=3] tree2Subset[checkFlags=="(E,f)"&is.na(share)&(availability.child<=0|is.na(availability.child)),message:="Missing prot share, neg avail, recalculated"] tree2Subset[checkFlags=="(E,f)"&is.na(share)&availability.child>0,severity:=3] tree2Subset[checkFlags=="(E,f)"&is.na(share)&availability.child>0,message:="Missing prot share recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] } return(tree2Subset) } ############ fun13 # 2. linesT>1 # B. NOT All protected line # b. Yes neg Av in No Protected # 1. No neg Av in Protected # i. No Missing fun13=function(tree2Subset,case="2.B.b.1.i"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share)] # there is a difference if the sum of protected is >1 if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)",severity:=2] tree2Subset[checkFlags=="(E,f)",message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[!(checkFlags=="(E,f)"), negShare:=1/freq] tree2Subset[!(checkFlags=="(E,f)"), sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[!(checkFlags=="(E,f)"), tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare-shareProt*(negShare), (tempAvailability / sum(tempAvailability, na.rm = TRUE)))-shareProt*(tempAvailability / sum(tempAvailability, na.rm = TRUE))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags!="(E,f)",severity:=as.integer(1)] tree2Subset[checkFlags!="(E,f)",message:="only not prot shares recalculated"] tree2Subset[checkFlags=="(E,f)",severity:=as.integer(0)] tree2Subset[checkFlags=="(E,f)",message:="prot share"] } return(tree2Subset) } ############ fun14 # 2. linesT>1 # B. NOT All protected line # b. Yes neg Av in No Protected # 1. No neg Av in Protected # ii. Yes Missing fun14=function(tree2Subset,case="2.B.b.1.ii"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share,na.rm=T)] # there is a difference if the sum of protected is >1 if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)",severity:=3] tree2Subset[checkFlags=="(E,f)",message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[!(checkFlags=="(E,f)"), negShare:=1/freq] tree2Subset[!(checkFlags=="(E,f)"), sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[!(checkFlags=="(E,f)"), tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare-shareProt*(negShare), (tempAvailability / sum(tempAvailability, na.rm = TRUE)))-shareProt*(tempAvailability / sum(tempAvailability, na.rm = TRUE))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&!(is.na(share)),severity:=1] tree2Subset[checkFlags=="(E,f)"&!(is.na(share)),message:="valid prot share"] tree2Subset[checkFlags=="(E,f)"&is.na(share),severity:=2] tree2Subset[checkFlags=="(E,f)"&is.na(share),message:="Missing prot share, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] } return(tree2Subset) } ############ fun15 # 2. linesT>1 # B. NOT All protected line # b. Yes neg Av in No Protected # 2. Yes neg Av in Protected # i. No Missing fun15=function(tree2Subset,case="2.B.b.2.i"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share)] # there is a difference if the sum of protected is >1 if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),message:="sum of prot shares>1, neg availlability, recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0,severity:=2] tree2Subset[checkFlags=="(E,f)"&availability.child>0,message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[!(checkFlags=="(E,f)"), negShare:=1/freq] tree2Subset[!(checkFlags=="(E,f)"), sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[!(checkFlags=="(E,f)"), tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare-shareProt*(negShare), (tempAvailability / sum(tempAvailability, na.rm = TRUE)))-shareProt*(tempAvailability / sum(tempAvailability, na.rm = TRUE))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags!="(E,f)",severity:=as.integer(1)] tree2Subset[checkFlags!="(E,f)",message:="only not prot shares recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),severity:=as.integer(1)] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child)),message:="prot share, neg avail"] tree2Subset[checkFlags=="(E,f)"&availability.child>0,severity:=as.integer(0)] tree2Subset[checkFlags=="(E,f)"&availability.child>0,message:="prot share"] } return(tree2Subset) } ############ fun16 # 2. linesT>1 # B. NOT All protected line # b. Yes neg Av in No Protected # 2. Yes neg Av in Protected # ii. YES Missing fun16=function(tree2Subset,case="2.B.b.2.ii"){ shareProt=tree2Subset[checkFlags=="(E,f)",sum(share,na.rm=T)] # there is a difference if the sum of protected is >1 if(shareProt>1){ tree2Subset[,newShare:=round(availability.child/sum(availability.child,na.rm = TRUE),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[, negShare:=1/freq] tree2Subset[,sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[,tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[,newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare, (tempAvailability / sum(tempAvailability, na.rm = TRUE)))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),message:="sum of prot shares>1, neg availlability, missing Share, recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),message:="sum of prot shares>1, neg availlability,recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0&is.na(share),severity:=2] tree2Subset[checkFlags=="(E,f)"&availability.child>0&is.na(share),message:="sum of prot shares>1, missing share, recalculated"] tree2Subset[checkFlags=="(E,f)"&availability.child>0,severity:=2] tree2Subset[checkFlags=="(E,f)"&availability.child>0,message:="sum of prot shares>1, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] }else{ tree2Subset[checkFlags!="(E,f)",newShare:=round(availability/sum(availability,na.rm = TRUE)-shareProt*(availability/sum(availability,na.rm = TRUE)),4)] freqChild= data.table(table(tree2Subset[, get("measuredItemChildCPC")])) setnames(freqChild, c("V1","N"), c("measuredItemChildCPC", "freq")) tree2Subset=merge(tree2Subset, freqChild , by="measuredItemChildCPC") tree2Subset[!(checkFlags=="(E,f)"), negShare:=1/freq] tree2Subset[!(checkFlags=="(E,f)"), sumPositiveAvail:=sum(availability.child*ifelse(availability.child>0,1,0),na.rm=TRUE),by = c("measuredItemChildCPC")] tree2Subset[!(checkFlags=="(E,f)"), tempAvailability:=ifelse(availability.child<=0|is.na(availability.child),negShare*sumPositiveAvail,availability)] tree2Subset[!(checkFlags=="(E,f)")|(is.na(share)), newShare := ifelse(tempAvailability==0|is.na(tempAvailability),negShare-shareProt*(negShare), (tempAvailability / sum(tempAvailability, na.rm = TRUE)))-shareProt*(tempAvailability / sum(tempAvailability, na.rm = TRUE))] tree2Subset[,c("freq","tempAvailability","sumPositiveAvail","negShare"):=NULL] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),severity:=1] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&!(is.na(share)),message:="neg, avail, valid prot share"] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),severity:=2] tree2Subset[checkFlags=="(E,f)"&(availability.child<=0|is.na(availability.child))&is.na(share),message:="Neg avail, Missing prot share, recalculated"] tree2Subset[checkFlags=="(E,f)"&(availability.child>0)&!(is.na(share)),severity:=1] tree2Subset[checkFlags=="(E,f)"&(availability.child>0)&!(is.na(share)),message:="valid prot share"] tree2Subset[checkFlags=="(E,f)"&(availability.child>0)&is.na(share),severity:=3] tree2Subset[checkFlags=="(E,f)"&(availability.child>0)&is.na(share),message:="Missing prot share, recalculated"] tree2Subset[checkFlags!="(E,f)",severity:=1] tree2Subset[checkFlags!="(E,f)",message:="also prot shares recalculated"] } return(tree2Subset) } ############################################################ ############### Run the alternative case ############## ############################################################ tree2Subset = switch(case, "1.A.a"= fun1(tree2Subset,case), "1.A.b" = fun2(tree2Subset,case), "1.B.a" = fun3(tree2Subset,case), "1.B.b" = fun4(tree2Subset,case), "2.A.a.1" = fun5(tree2Subset,case), "2.A.a.2" = fun6(tree2Subset,case), "2.A.b.1" = fun7(tree2Subset,case), "2.A.b.2" = fun8(tree2Subset,case), "2.B.a.1.i" = fun9(tree2Subset,case), "2.B.a.1.ii" = fun10(tree2Subset,case), "2.B.a.2.i" = fun11(tree2Subset,case), "2.B.a.2.ii" = fun12(tree2Subset,case), "2.B.b.1.i" = fun13(tree2Subset,case), "2.B.b.1.ii" = fun14(tree2Subset,case), "2.B.b.2.i" = fun15(tree2Subset,case), "2.B.b.2.ii" = fun16(tree2Subset,case) ) tree2Subset[,share:=ifelse(!is.na(newShare),round(newShare,4),round(share,4))] tree2Subset[,newShare:=NULL] setcolorder(tree2Subset,c("measuredItemParentCPC", "geographicAreaM49", "measuredItemChildCPC", "timePointYears", "flagObservationStatus", "flagMethod", "share", "extractionRate", "availability", "checkFlags", "availability.child", "shareSum","severity", "message")) tree2Subset[share==0, message:="Share = 0 removes connection"] tree2Subset[share==0, severity:=5] return(tree2Subset) } <file_sep>/modules/SuabalancedOutliersElements/main.R ##' #Balanced SUA element outliers detection ##' ##' ##' ##' **Author: <NAME>** ##' ##' **Description:** ##' ##' This module is designed to detect outliers in SUA balanced for all elements. ##' ##' **Inputs:** ##' ##' * sua balanced ##' ##' **Flag assignment:** ##' ##' I e ## load the library library(faosws) library(data.table) library(faoswsUtil) library(sendmailR) library(dplyr) library(faoswsUtil) #library(faoswsStandardization) library(faoswsFlag) library(faoswsStandardization) if(CheckDebug()){ message("Not on server, so setting up environment...") library(faoswsModules) ## SETT <- ReadSettings("modules/outlierImputation/sws.yml") SETT <- ReadSettings("C:/Users/VALDIVIACR/Desktop/FAO/R/version faostandardization october 2018/faoswsStandardization/modules/fullStandardizationAndBalancing/sws.yaml") R_SWS_SHARE_PATH <- SETT[["share"]] ## Get SWS Parameters SetClientFiles(dir = SETT[["certdir"]]) GetTestEnvironment( baseUrl = SETT[["server"]], token = SETT[["token"]] ) } #startYear = as.numeric(swsContext.computationParams$startYear) startYear = as.numeric(2011) #endYear = as.numeric(swsContext.computationParams$endYear) endYear = as.numeric(2017) stopifnot(startYear <= endYear) yearVals = startYear:endYear ##' Get data configuration and session sessionKey = swsContext.datasets[[1]] sessionCountries = getQueryKey("geographicAreaM49", sessionKey) geoKeys = GetCodeList(domain = "agriculture", dataset = "aproduction", dimension = "geographicAreaM49")[type == "country", code] ##Select the countries based on the user input parameter selectedGEOCode =sessionCountries ######################################### ##### Pull from SUA unbalanced and balanced data ##### ######################################### message("Pulling SUA unbalanced Data") #take geo keys geoDim = Dimension(name = "geographicAreaM49", keys = selectedGEOCode) #Define element dimension. These elements are needed to calculate net supply (production + net trade) eleKeys <- GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredElementSuaFbs") eleKeys = eleKeys[, code] eleDim <- Dimension(name = "measuredElementSuaFbs", keys = c("5510","5610","5071","5023","5910","5016","5165","5520","5525","5164","5166","5141","664","5113")) #Define item dimension itemKeys = GetCodeList(domain = "suafbs", dataset = "sua_unbalanced", "measuredItemFbsSua") itemKeys = itemKeys[, code] itemDim <- Dimension(name = "measuredItemFbsSua", keys = itemKeys) # Define time dimension timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_unbalanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) data_unbal = data = GetData(key,omitna=F) ######################################### ##### Pull from SUA balanced data ##### ######################################### timeDim <- Dimension(name = "timePointYears", keys = as.character(yearVals)) #Define the key to pull SUA data key = DatasetKey(domain = "suafbs", dataset = "sua_balanced", dimensions = list( geographicAreaM49 = geoDim, measuredElementSuaFbs = eleDim, measuredItemFbsSua = itemDim, timePointYears = timeDim )) data_bal = data = GetData(key,omitna=F) #Identify cpc codes of food and primary commodities commDef = ReadDatatable("utilization_table_2018") food=commDef$cpc[commDef[,food_item=="X"]] primary=commDef$cpc[commDef[,primary_item=="X"]] #TWO SIMULTANEOUS CRITERIA FOR DETECTING OUTLIERS #1.THE RATIO BETWEEN VALUE AND HISTORIAL VALUE (RELATIVE TO YEARS 2011-2013) HAS TO BE WITHIN 2 AND 0.5 #2.RATIO BETWEEN VALUE AND SUPPLY HAS TO BE WITHIN 15 PERCENTAGE POINTS DIFFERENCE FROM HISTORICAL RATIO OF VALUE TO SUPPLY (RELATIVE TO YEARS 2011-2013) #Keep only data for years 2011-2013 to calculate historical values using data from sua unbalanced data_unbal=data_unbal[timePointYears>=2011 & timePointYears<=2013] data_unbal <-data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua, measuredElementSuaFbs) %>% dplyr::mutate(Meanold=mean(Value,na.rm=T)) data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(prod=sum(Value[measuredElementSuaFbs==5510])) data_unbal$prod[is.na(data_unbal$prod)]<-0 data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(imp=sum(Value[measuredElementSuaFbs==5610])) data_unbal$imp[is.na(data_unbal$imp)]<-0 data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(exp=sum(Value[measuredElementSuaFbs==5910])) data_unbal$exp[is.na(data_unbal$exp)]<-0 data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(stock=sum(Value[measuredElementSuaFbs==5071])) data_unbal$stock[is.na(data_unbal$stock)]<-0 data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp-exp-stock) data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio_old=Value/supply) data_unbal<- data_unbal %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs) %>% dplyr::mutate(mean_ratio=mean(ratio_old,na.rm=T)) data_unbal=data_unbal[,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "Meanold", "mean_ratio")] data_unbal<-unique(data_unbal) data = merge(data_bal, data_unbal, by =c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua") ) data=data[measuredItemFbsSua%in%food] data$Meanold[is.na(data$Meanold)]<-0 data$Value[is.na(data$Value)]<-0 data$mean_ratio[is.na(data$mean_ratio)]<-0 data<-data%>% dplyr::mutate(ratio_val=(Value/Meanold)) data<- data%>% dplyr::mutate(outlier= (ratio_val>2 | ratio_val<0.5) & timePointYears>2013) data<- data%>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(prod=sum(Value[measuredElementSuaFbs==5510])) data$prod[is.na(data$prod)]<-0 data<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(imp=sum(Value[measuredElementSuaFbs==5610])) data$imp[is.na(data$imp)]<-0 data<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(exp=sum(Value[measuredElementSuaFbs==5910])) data$exp[is.na(data$exp)]<-0 data<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(stock=sum(Value[measuredElementSuaFbs==5071])) data$stock[is.na(data$stock)]<-0 data<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,timePointYears) %>% dplyr::mutate(supply=prod+imp-exp-stock) data<- data %>% group_by(geographicAreaM49,measuredItemFbsSua,measuredElementSuaFbs,timePointYears) %>% dplyr::mutate(ratio_supp=Value/supply) data<-data%>% dplyr::mutate(outl_on_supp=(abs(ratio_supp-mean_ratio)>=0.1)) data=as.data.table(data) data=data[measuredElementSuaFbs!=5610 & measuredElementSuaFbs!=5910 & measuredElementSuaFbs!=5071 & measuredElementSuaFbs!=664] data=data[!(measuredElementSuaFbs==5510 & measuredItemFbsSua%in%primary) ] data=data[!(measuredElementSuaFbs==5016 & Value!=0 & Meanold==0) ] setDT(data) #imbToSend=subset(data,timePointYears>=2014 & ((outlier==T & outl_on_supp==T & (measuredElementSuaFbs==5520|measuredElementSuaFbs==5525|measuredElementSuaFbs==5016|measuredElementSuaFbs==5023|measuredElementSuaFbs==5165|measuredElementSuaFbs==5141))|(outlier==T & (measuredElementSuaFbs==5510))|(Value==0 & Meanold!=0)|(Value!=0 & Meanold==0)|(abs(Meanold-Value)>50000 & outlier==T))) imbToSend=subset(data,timePointYears>=2014 & ((outlier==T & outl_on_supp==T & (measuredElementSuaFbs==5520|measuredElementSuaFbs==5525|measuredElementSuaFbs==5016|measuredElementSuaFbs==5023|measuredElementSuaFbs==5165|measuredElementSuaFbs==5141) & (abs(Meanold-Value)>10000))|(outlier==T & (measuredElementSuaFbs==5510) & (abs(Meanold-Value)>10000)))) setDT(imbToSend) imbToSend<-imbToSend%>% dplyr::mutate(keep=(Value==0 & Meanold!=0)) imbToSend<-imbToSend%>% dplyr::mutate(keep2=(Value!=0 & Meanold==0)) imbToSend=subset(imbToSend, (Value>10000 & keep==FALSE & keep2==FALSE)) if (nrow(imbToSend) > 0) { setnames(imbToSend,"Meanold","Historical_value2011_2013") imbToSend=imbToSend[,c("geographicAreaM49", "measuredElementSuaFbs", "measuredItemFbsSua", "timePointYears", "Value", "flagObservationStatus", "flagMethod", "Historical_value2011_2013")] setDT(imbToSend) #data.table::setorder(imbToSend,-perc.imbalance) imbToSend=nameData("suafbs","sua_balanced",imbToSend) bodyImbalances= paste("The Email contains the list of outliers for the following elements: Production, Food, Feed, Seed, Loss, Processed, Industrial Use. Please check them.", sep='\n') sendMailAttachment(setDT(imbToSend),"Outliers_elements_SUA_bal",bodyImbalances) print("Outliers found, please check email.") } else { print("No outliers found.") } <file_sep>/tests/testthat/test-settings_files.R context("Settings files") sname <- "sws.yml" ## Helper functions # Use project path instead of test path cp <- function(path){ paste0("../../", path) } # Add .example to settings files addEx <- function(name, extension = ".example"){ paste0(name, extension) } # Check if settings file exists setExists <- function(name){ file.exists(cp(name)) } # Test to see if example file is missing settingHasNoExample <- function(file){ setExists(file) && !setExists(addEx(file)) } # Get names of fields in settings file getSettingFields <- function(name){ names(read.dcf(cp(name))[1,]) } ## TESTS test_that("Settings file is never present without example", { expect_false(settingHasNoExample(sname)) }) <file_sep>/R/plotCommodityTrees.R ##' Plot Commodity Trees ##' ##' This function generates plots for each of the commodity trees defined ##' in a commodity tree object. A separate plot is given for each node that ##' has no parent, and this should allow for the production of a wheat tree, ##' a milk tree, etc. ##' ##' @param commodityTree A data.table with parent and child node IDs ##' (corresponding to the IDs in nodes) which specify the commodity tree ##' structure. Additionally, there should be a column with extraction rate ##' data and a column with shares data. ##' @param parentColname The column name of commodityTree which contains the ID ##' of the parent node. ##' @param childColname The column name of commodityTree which contains the ID ##' of the child node. ##' @param extractionColname The column name of commodityTree which contains ##' the extraction rate data. ##' @param dir The directory where the commodity trees should be saved. ##' @param prefix The prefix to add to the name of the plot(s) which will be ##' saved to dir. One plot is created for each commodity tree. ##' @param adjExtractionRates Logical. Typically, the extraction rates are ##' stored as percentages multiplied by 10000, i.e. 5% is represented as ##' 0.05*10000 = 500. If TRUE, the function converts them to percentages. ##' ##' @return No object is returned, but image files of the plots are written ##' out to .png files. The input parameter dir specifies where these files ##' will be placed. ##' ##' @export ##' plotCommodityTrees = function(commodityTree, parentColname, childColname, extractionColname, dir = getwd(), prefix = "commodity_tree", adjExtractionRates = TRUE){ ## Data Quality Checks stopifnot(is(commodityTree, "data.table")) stopifnot(c(parentColname, childColname, extractionColname) %in% colnames(commodityTree)) if(any(commodityTree[, .N, by = c(parentColname, childColname)][, N] > 1)) stop("This function is not designed to work for multiple countries, ", "years, etc. Please subset the data and loop to generate ", "multiple such trees.") if(adjExtractionRates) commodityTree[, c(extractionColname) := get(extractionColname)/10000] ## Find the top nodes. topNodes = setdiff(commodityTree[[parentColname]], commodityTree[[childColname]]) ## Now, we'll assume that each topNode corresponds ot a unique commodity ## tree. ## ## Assign the edges to the approriate tree. Any child node receives the ## treeID of it's parent, if available. Some children may be children ## of multiple parents and hence (possibly) multiple treeID's. In those ## cases, we'll need to group treeID's into the same group. commodityTree[, treeID := NA_character_] commodityTree[get(parentColname) %in% topNodes, treeID := as.character(get(parentColname))] while(any(is.na(commodityTree[, treeID]))){ ids = commodityTree[!is.na(treeID), .N, by = c(childColname, "treeID")] ids[, N := NULL] setnames(ids, c(childColname, "treeID"), c(parentColname, "newTreeID")) commodityTree = merge(commodityTree, ids, by = parentColname, all.x = TRUE, allow.cartesian = TRUE) commodityTree[is.na(treeID), treeID := newTreeID] commodityTree[, newTreeID := NULL] } for(currentTreeID in unique(commodityTree$treeID)){ png(paste0(dir, "/", prefix, "_commodity_tree_", currentTreeID, ".png"), width = 10, height = 10, units = "in", res = 400) plotSingleTree(commodityTree[treeID == currentTreeID, ], parentColname, childColname, extractionColname) dev.off() } }
5d3eecc9a91fede26ee2983dd7ef377b5c374710
[ "Markdown", "R" ]
64
R
SWS-Methodology/faoswsStandardization
95a140446b6a2c75676d0dc299e7b63007d566a3
87a3c32bec5e9c7c291a6bbb63612570f4023755
refs/heads/master
<repo_name>cza801/LiriApp<file_sep>/README.md # LiriApp A Siri like command line <file_sep>/keys.js console.log('Content is loading...'); exports.twitterKeys = { consumer_key: 'tWDlCycv45UiB0y9sBeKbQEGE', consumer_secret: '<KEY>', access_token_key: '<KEY>', access_token_secret: '<KEY>', }<file_sep>/liri.js //the code that grabs the keys var keys = require("./keys.js"); // variables to shorten the key callt var twKeys = keys.twitterKeys; // This is all all my NPM homies var inquirer = require("inquire"); var twitter = require("twitter"); var request = require("request"); // var fs = request("fs"); // user input var input = process.argv[2]; var movieTitle = process.argv[3]; // Attempting to get more than 1 word responces. // var movieTitle; // for (var i = 1; i < process.argv.length; i++) { // movieTitle = process.argv[i]; // } //User commands if (input === "my-tweets") { return mytweets(); } function mytweets() { var twitterClient = new twitter ({ consumer_key: twKeys.consumer_key, consumer_secret: twKeys.consumer_secret, access_token_key: twKeys.access_token_key, access_token_secret: twKeys.access_token_secret, }); var parameters = { screen_name: "netflix", count: 20, trim_user: false, } twitterClient.get('statuses/user_timeline', parameters, function(error, timeline, response){ if(error){ console.log(error); } else { for(tweet in timeline){ var date = new Date(timeline[tweet].created_at); console.log('Tweet # : ' + (parseInt(tweet)+1)); console.log('Date And Time: ' + date.toString().slice(0, 24)); console.log('Tweet: ' + timeline[tweet].text); console.log('___________________________________') } } }); } if (input === "movie-this") { omdbInfo(movieTitle); } function omdbInfo(movieTitle) { request("http://www.omdbapi.com/?t=" + movieTitle + "&y=&plot=short&apikey=40e9cece", function (error, response, body) { if(error){ console.log(error); }; omdbReturn = JSON.parse(body); console.log(omdbReturn.Title); console.log("Year: " + omdbReturn.Year); console.log( "IMDB Rating: " + omdbReturn.imdbRating); console.log("Rotten Tomatoes Rating: " + omdbReturn.Ratings[1].Value); console.log("Country produced in: " + omdbReturn.Country); console.log("Language: " + omdbReturn.Language); console.log("Plot: " + omdbReturn.Plot); console.log("Actors: " + omdbReturn.Actors); // console.log(omdbReturn); }) }
5dd6a948d53a82cc01549a3fd424fff7f8cc6dc1
[ "Markdown", "JavaScript" ]
3
Markdown
cza801/LiriApp
1b42253915f8acc735d8c93e99633b47281e45ab
5d82d88961028409c0cdcf61844b4395a9bc76da
refs/heads/master
<repo_name>rutujadudhagundi/demorepo<file_sep>/Xyz.java public class Xyz { public void display() { System.out.println("From XYZ class"); } }
01765a39d69f36d6932af2fd234634ae707dad58
[ "Java" ]
1
Java
rutujadudhagundi/demorepo
a64515226ccb75958b6d9a6c44d3879564445643
5c88e3078df0d7e69c7a9bf06d089b04bf760146
refs/heads/master
<repo_name>Plusid/delegate-calculator-plugin<file_sep>/src/components/modals/DelegateModal.js const utils = require('../../utils') module.exports = { template: ` <ModalWindow container-classes="max-w-md w-md" @close="emitClose" > <template #header> <div class="flex items-center"> <h2>{{ delegate.name }}</h2> <span v-if="!delegate.isClaimed" v-tooltip="{ content: 'The delegate has not claimed his account and the information shown is likely to be inaccurate', trigger: 'hover', classes: 'text-xs max-w-xs', placement: 'right' }" class="bg-red text-white text-xs text-center font-semibold rounded py-1 px-2 ml-2" > Unclaimed </span> <span v-tooltip="{ content: delegate.isPrivate ? 'You may not receive any rewards from this delegate' : '', trigger: 'hover', classes: 'text-xs', placement: 'right' }" class="text-white text-xs text-center font-semibold rounded py-1 px-2 ml-2" :class="delegate.isPrivate ? 'bg-red' : 'bg-green'" > {{ delegate.isPrivate ? 'Private' : 'Public' }} </span> </div> </template> <ListDivided> <ListDividedItem label="Rank" :value="delegate.rank" /> <ListDividedItem label="Votes" :value="formatCurrency(delegate.votes, 'INF')" /> <ListDividedItem v-if="delegate.website" label="Website" :value="delegate.website" /> </ListDivided> <h3 class="mt-4 mb-3">Payout</h3> <ListDivided> <ListDividedItem label="Shared Percentage" :value="delegate.payout.percentage + '%'" /> <ListDividedItem label="Interval" :value="delegate.payout.interval + 'h'" /> <ListDividedItem v-if="delegate.payout.minimum" label="Minimum Payout" :value="formatCurrency(delegate.payout.minimum, 'INF')" /> <ListDividedItem v-if="delegate.payout.maximum" label="Maximum Payout" :value="formatCurrency(delegate.payout.minimum, 'INF')" /> <ListDividedItem v-if="delegate.payout.payout_minimum_vote_amount" label="Minimum Required Vote-Weight" :value="formatCurrency(delegate.payout.payout_minimum_vote_amount, 'INF')" /> <ListDividedItem v-if="delegate.payout.payout_maximum_vote_amount" label="Maximum Regarded Vote-Weight" :value="formatCurrency(delegate.payout.payout_maximum_vote_amount, 'INF')" /> </ListDivided> <h3 class="mt-4 mb-3">Contributions</h3> <div v-if="delegate.contributions.count"> <ListDivided> <ListDividedItem label="Count" :value="delegate.contributions.count" /> <ListDividedItem label="Days Since Last" :value="delegate.contributions.last || '0'" /> <ListDividedItem label="Status" :value="statusText" /> </ListDivided> </div> <span v-else> This delegate hasn't published any contributions. </span> <template #footer> <footer class="flex items-center rounded-lg mt-2 text-sm shadow bg-yellow-lighter text-grey-darkest px-16 py-8"> <p> Visit <span class="inline-flex items-center font-semibold"> {{ url }} <ButtonClipboard :value="url" class="text-theme-modal-footer-button-text pl-1" /> </span> for more information </p> </footer> </template> </ModalWindow> `, props: { delegate: { type: Object, required: true }, callback: { type: Function, required: true } }, computed: { profile () { return walletApi.profiles.getCurrent() }, statusText () { return utils.upperFirst(this.delegate.contributions.status) }, url () { return `https://api.infinitysolutions.io/api/v2/delegates/${this.delegate.slug}` } }, methods: { executeCallback (event) { this.callback({ component: 'DelegateModal', event }) }, emitClose () { this.executeCallback('close') }, formatCurrency (value, currency) { return utils.formatter_currency(Number(value) / 1e5, currency, this.profile.language) } } } <file_sep>/src/index.js module.exports = { register () { this.routes = [ { path: '/calculator', name: 'calculator', component: 'Calculator' } ] this.menuItems = [ { routeName: 'calculator', title: 'INF Delegate Calculator' } ] }, getComponentPaths () { return { 'Calculator': 'pages/index.js' } }, getRoutes () { return this.routes }, getMenuItems () { return this.menuItems } } <file_sep>/src/components/DelegateTable.js const utils = require('../utils') module.exports = { template: ` <TableWrapper class="w-full" :rows="rows" :columns="columns" :has-pagination="true" :current-page="currentPage" :per-page="perPage" :per-page-dropdown="[25]" > <template slot-scope="data" > <div v-if="data.column.field === 'name'"> <div class="flex flex-col"> <div class="flex items-center"> <button class="flex items-center text-blue hover:underline" @click="emitOpenDelegateModal(data.row.name)" > {{ data.row.name }} </button> <span v-if="data.row.isVoted" class="ml-2 bg-red text-white text-xs text-center font-semibold rounded py-1 px-2" > Voted </span> </div> <div class="flex font-semibold text-xs text-theme-page-text-light"> <span v-if="!data.row.isClaimed" v-tooltip="{ content: 'The delegate has not claimed his account and the information shown is likely to be inaccurate', trigger: 'hover', classes: 'text-xs max-w-xs', placement: 'right' }" class="mt-1 pr-1" > Unclaimed </span> <div v-else class="flex mt-1" > <span v-tooltip="{ content: data.row.isPrivate ? 'You may not receive any rewards from this delegate' : '', trigger: 'hover', classes: 'text-xs', placement: 'right' }" class="pr-1" > {{ data.row.isPrivate ? 'Private' : 'Public' }} </span> <span v-if="showContributorStatus(data.row.contributions)" v-tooltip="{ content: getContributionsTooltip(data.row.contributions.last), trigger: 'hover', classes: 'text-xs', placement: 'right' }" class="ml-1 pl-2 pr-1 border-l border-theme-line-separator" > {{ getContributionsStatus(data.row.contributions.status) }} </span> </div> </div> </div> </div> <div v-else-if="data.column.field === 'rewards'" class="flex flex-col" > {{ data.row.rewards ? data.row.rewards.toFixed(8) : 'None' }} <span v-if="data.row.rewardsDiff" class="mt-1 font-semibold text-xs" :class="data.row.rewardsDiff < 0 ? 'text-red' : 'text-green'" > <span v-if="data.row.rewardsDiff > 0">+</span>{{ data.row.rewardsDiff.toFixed(8) }} </span> </div> <div v-else-if="data.column.field === 'weeklyRewards'" class="flex flex-col" > {{ data.row.rewards ? (data.row.rewards * 7).toFixed(8) : 'None' }} <span v-if="data.row.rewardsDiff" class="mt-1 font-semibold text-xs" :class="data.row.rewardsDiff < 0 ? 'text-red' : 'text-green'" > <span v-if="data.row.rewardsDiff > 0">+</span>{{ (data.row.rewardsDiff * 7).toFixed(8) }} </span> </div> <span v-else-if="data.column.field === 'payout.percentage'"> {{ data.row.payout.percentage }}% </span> <span v-else-if="data.column.field === 'payout.interval'"> {{ data.row.payout.interval }}h </span> <span v-else> {{ data.formattedRow[data.column.field] }} </span> </template> </TableWrapper> `, props: { rows: { type: Array, required: true }, currentPage: { type: Number, required: true }, perPage: { type: Number, required: true }, callback: { type: Function, required: true } }, computed: { columns () { return [ { label: 'Name', field: 'name' }, { label: 'Daily Rewards', field: 'rewards', type: 'number' }, { label: 'Weekly Rewards', field: 'weeklyRewards', type: 'number', sortFn: this.sortByRewards }, { label: 'Payout', field: 'payout.percentage', type: 'number' }, { label: 'Interval', field: 'payout.interval', type: 'number' } ] }, profile () { return walletApi.profiles.getCurrent() } }, methods: { executeCallback (event, options) { this.callback({ component: 'DelegateTable', event, options }) }, emitOpenDelegateModal (name) { this.executeCallback('openDelegateModal', { name }) }, sortByRewards (x, y, col, rowX, rowY) { return rowX.rewards.toString().localeCompare(rowY.rewards.toString(), undefined, { sensitivity: 'base', numeric: true }) }, showContributorStatus ({ count, status }) { return count && status !== 'inactive' }, getContributionsTooltip (last) { switch (last) { case 0: return 'The last contribution was published today' case 1: return `The last contribution was published ${last} day ago` default: return `The last contribution was published ${last} days ago` } }, getContributionsStatus (status) { return `${utils.upperFirst(status)} Contributor` } } } <file_sep>/src/pages/index.js const DelegateModal = require('../components/modals/DelegateModal') const DelegateTable = require('../components/DelegateTable') const DisclaimerModal = require('../components/modals/DisclaimerModal') const Footer = require('../components/Footer') const Header = require('../components/Header') const ImageService = require('../services/image.service.js') module.exports = { template: ` <div class="flex flex-col flex-1 overflow-y-auto"> <div v-if="!hasWallets || hasWrongNetwork" class="relative flex flex-col flex-1 justify-center items-center rounded-lg bg-theme-feature" > <div class="flex flex-col items-center"> <img :src="logoImage" class="mb-10 rounded-lg"> <template v-if="!hasWallets"> <p class="mb-5"> Your profile has no wallets yet. </p> <button class="flex items-center text-blue hover:underline" @click="goTo('wallet-import')" > Import a wallet now </button> </template> <template v-else> <p class="mb-5"> This plugin works only on the INF Main network. </p> <button class="flex items-center text-blue hover:underline" @click="goTo('profiles')" > Select a different profile </button> </template> </div> </div> <div v-else-if="wallet" class="flex flex-col flex-1 overflow-y-hidden" > <Header :wallet="wallet" :callback="handleEvent" /> <div class="flex flex-col flex-1 p-10 rounded-lg bg-theme-feature overflow-y-auto"> <div class="flex flex-1"> <div v-if="isLoading" class="relative flex items-center mx-auto w-md" > <div class="mx-auto"> <Loader /> </div> </div> <div v-else class="w-full" > <DelegateTable v-if="delegates.length" :rows="delegates" :current-page="1" :per-page="25" :callback="handleEvent" /> </div> </div> </div> </div> <DelegateModal v-if="showDelegateModal" :delegate="selectedDelegate" :callback="handleEvent" /> <DisclaimerModal v-if="!options.hasAcceptedDisclaimer" :callback="handleEvent" /> <Footer /> </div> `, components: { DelegateModal, DisclaimerModal, DelegateTable, Footer, Header }, data: () => ({ address: '', isLoading: false, wallet: { address: '', balance: '', vote: '' }, delegateData: [], delegates: [], selectedDelegate: null, showDelegateModal: false }), async mounted () { this.address = walletApi.storage.get('address') this.wallet = this.wallets.find(wallet => wallet.address === this.address) if (!this.wallet) { try { this.wallet = this.wallets[0] } catch (error) { // } } if (this.wallet) { try { this.isLoading = true await this.fetchDelegates() if (!Object.prototype.hasOwnProperty.call(this.wallet, 'vote')) { try { const { data } = await walletApi.peers.current.get(`wallets/${this.wallet.address}`) this.wallet.vote = data.vote } catch (error) { walletApi.alert.error('Failed to fetch wallet vote') } } this.calculateTableData() } catch (error) { walletApi.alert.error('Failed to fetch delegate data') } finally { this.isLoading = false } } }, computed: { logoImage () { return ImageService.image('logo') }, profile () { return walletApi.profiles.getCurrent() }, wallets () { return this.profile.wallets }, hasWallets () { return !!(this.wallets && this.wallets.length) }, hasWrongNetwork () { return this.profile.network.token !== 'INF' }, options () { return walletApi.storage.getOptions() } }, methods: { async handleEvent ({ component, event, options }) { try { await this[`__handle${component}Event`](event, options) } catch (error) { console.log(`Missing event handler for component: ${component}`) } }, async __handleHeaderEvent (event, options) { if (event === 'addressChange') { this.address = options.address // TODO: move to watcher in future version walletApi.storage.set('address', this.address) this.wallet = this.wallets.find(wallet => wallet.address === this.address) if (!Object.prototype.hasOwnProperty.call(this.wallet, 'vote')) { try { const { data } = await walletApi.peers.current.get(`wallets/${this.address}`) this.wallet.vote = data.vote } catch (error) { walletApi.alert.error('Failed to fetch wallet vote') } } this.calculateTableData() } }, __handleDelegateTableEvent (event, options) { if (event === 'openDelegateModal') { this.showDelegateModal = true const delegate = this.delegates.find(delegate => delegate.name === options.name) this.selectedDelegate = { ...delegate, votes: Number(delegate.votes) - Number(this.wallet.balance) } } }, __handleDelegateModalEvent (event, options) { if (event === 'close') { this.showDelegateModal = false this.selectedDelegate = null } }, __handleDisclaimerModalEvent (event) { if (event === 'cancel') { this.goTo('dashboard') } else if (event === 'confirm') { walletApi.storage.set('hasAcceptedDisclaimer', true) } }, goTo (route) { walletApi.route.goTo(route) }, async fetchDelegates () { const { body } = await walletApi.http.get('https://api.infinitysolutions.io/api/delegates', { query: { limit: 25 }, json: true }) this.delegateData = body.data.map(delegate => { return { rank: delegate.rank, name: delegate.name, slug: delegate.slug, votes: delegate.delegateStatistics.voting_power, publicKey: delegate.public_key, website: delegate.website, contributions: { count: delegate.contributionsCount, last: delegate.days_since_last_contribution, status: delegate.contribution_status }, payout: { percentage: delegate.payout_percent, interval: delegate.payout_interval, minimum: (delegate.payout_minimum && delegate.payout_minimum !== "0") ? delegate.payout_minimum : null, maximum: (delegate.payout_maximum && delegate.payout_maximum !== "0") ? delegate.payout_maximum : null, minVotes: (delegate.payout_minimum_vote_amount && delegate.payout_minimum_vote_amount !== "0") ? delegate.payout_minimum_vote_amount : null, maxVotes: (delegate.payout_maximum_vote_amount && delegate.payout_maximum_vote_amount !== "0") ? delegate.payout_maximum_vote_amount : null }, isPrivate: delegate.is_private, isClaimed: delegate.is_claimed } }) }, calculateTableData () { let delegates = this.delegateData.map(delegate => { const newDelegate = { ...delegate, isVoted: delegate.publicKey === this.wallet.vote } if (!newDelegate.isVoted) { newDelegate.votes = Number(delegate.votes) + Number(this.wallet.balance) } newDelegate.rewards = Number(this.wallet.balance) / Number(newDelegate.votes) * 422 * delegate.payout.percentage / 100 return newDelegate }) const votedDelegate = delegates.find(delegate => delegate.isVoted) if (votedDelegate) { delegates = delegates.map(delegate => { delegate.rewardsDiff = delegate.rewards - votedDelegate.rewards return delegate }) } this.delegates = delegates } } } <file_sep>/src/components/modals/DisclaimerModal.js module.exports = { template: ` <ModalConfirmation container-classes="max-w-md" title="Disclaimer" cancel-button="Cancel" continue-button="I understand" @cancel="emitCancel" @close="emitCancel" @continue="emitConfirm" > <div class="mb-6 text-grey-darker text-lg"> <p class="mb-3"> The information presented by this plugin is based on the data available on https://infinitysolutions.io and has been prepared for informational purposes only. </p> <p> Special thanks to delegates <span class="font-semibold">deadlock</span> and <span class="font-semibold">infinity developers</span> for building and maintaining https://infinitysolutions.io </p> </div> </ModalConfirmation> `, props: { callback: { type: Function, required: true } }, methods: { executeCallback (event) { this.callback({ component: 'DisclaimerModal', event }) }, emitCancel () { this.executeCallback('cancel') }, emitConfirm () { this.executeCallback('confirm') } } } <file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.4] - 2020-03-26 ### Fixed - Typos in variable names ## [1.0.3] - 2020-03-26 ### Fixed - Reload when changing address ## [1.0.2] - 2020-03-25 ### Added - Clipboard button for URL in delegate modal ## [1.0.1] - 2020-03-24 ### Added - Customized footer ### Changed - Wording of modal message ### Fixed - Adjusted minimum wallet version ## [1.0.0] - 2020-03-23 - Initial release
c370f7c5e6a1aa3318fbe3214a9ba9c0f05e8db8
[ "JavaScript", "Markdown" ]
6
JavaScript
Plusid/delegate-calculator-plugin
a8da81ae8c64aa45073d7e543deaabbbca88565e
e3afdddcd95bb4f17e75569839e2775265403601
refs/heads/master
<file_sep>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace StringProcessor.Tests { [TestClass] public class StringCalculatorTest { //private int ArrangeAct(string numbers) //{ // var calculator = new StringCalculator(); // return calculator.Add(numbers); //} //private StringCalculator _calculator = null; //重构用 #region 需求1:写一个方法,能够接收0,1,2个数字参数,用逗号“,”分隔的字符串。 [TestMethod] public void Add_NeedAddMethodWithStringParameters() { StringCalculator calculator = new StringCalculator();//refactor calculator.Add(string.Empty); Assert.IsTrue(true); } //step3 //[TestMethod] //public void When1NumberAreUsedThenNoException() //{ // StringCalculator calculator = new StringCalculator(); // calculator.Add("1"); // Assert.IsTrue(true); //} //[TestMethod] //public void When2NumbersAreUsedThenNoException() //{ // StringCalculator calculator = new StringCalculator(); // calculator.Add("1,2"); // Assert.IsTrue(true); //} //上面两个测试方法重构成下面一个方法 //step3 [TestMethod] //[DataRow("")] [DataRow("1")] [DataRow("1,2")] public void Add_WhenLessThan2NumbersAreUsed_NoException(string numbers) { StringCalculator calculator = new StringCalculator(); calculator.Add(numbers); Assert.IsTrue(true); } //step4 [TestMethod] [ExpectedException(typeof(FormatException))] public void Add_WhenNonNumberIsUsed_ThrowException() { StringCalculator calculator = new StringCalculator(); calculator.Add("1,X"); } //为满足 需求4:允许接收不固定数字个数的字符串。 //下面的测试已经不需要了 //[TestMethod] //[ExpectedException(typeof(ArgumentException), "参数应该是不能超过2个数字且用逗号‘,’分隔的字符串。")] //[DataRow("1,2,3")] //[DataRow("1,2,3,4")] //public void WhenMoreThan2NumbersAreUsedThenThrowException(string numbers) //{ // StringCalculator calculator = new StringCalculator(); // calculator.Add(numbers); //} #endregion //需求2:对于空字符串参数,方法将返回0。 [TestMethod] public void Add_WhenEmptyStringIsUsed_Return0() { StringCalculator calculator = new StringCalculator(); //refactor Assert.AreEqual(0, calculator.Add("")); } //step6 #region 需求3:方法返回字符串里所有数字的和。 [TestMethod] public void Add_ShouldReturnSumOf1Numbers() { StringCalculator calculator = new StringCalculator(); int sum = calculator.Add("1"); Assert.AreEqual(1, sum); } [TestMethod] public void Add_ShouldReturnSumOf2Numbers() { StringCalculator calculator = new StringCalculator(); int sum = calculator.Add("1,2"); Assert.AreEqual(1 + 2, sum); } [TestMethod] [DataRow(1, "1")] [DataRow(1 + 1, "1,1")] [DataRow(1 + 2, "1,2")] [DataRow(1 + 2 + 3, "1,2,3")] //需求4:允许接收不固定数字个数的字符串。 [DataRow(1 + 2 + 3 + 5, "1,2,3,5")] //需求4:允许接收不固定数字个数的字符串。 public void Add_ShouldReturnSumOfAllNumbers(int expected, string stringNumbers) { StringCalculator calculator = new StringCalculator(); int sum = calculator.Add(stringNumbers); Assert.AreEqual(expected, sum); } #endregion //需求5:允许 Add 方法处理数字之间的新分隔符 (而不是逗号) [TestMethod] [DataRow(1 + 2, "1\n2")] [DataRow(1 + 2 + 14, "\n1,2\n14")] public void Add_ShouldAllowNewLineAsSeparator(int expected, string stringNumbers) { StringCalculator calculator = new StringCalculator(); //int sum = calculator.Add("1,2\n5"); //重构 //Assert.AreEqual(1+2+5, sum); int sum = calculator.Add(stringNumbers); Assert.AreEqual(expected, sum); } [TestMethod] [DataRow(1 + 2 + 3 + 11, "//;\n1;2\n3;11")] [DataRow(1 + 2 + 3 + 11, "//|\n1|2\n3|11")] public void Add_ShouldSupportSeparator(int expected, string stringNumbers) { StringCalculator calculator = new StringCalculator(); //int sum = calculator.Add("//;\n1;2;\n14");//重构 //Assert.AreEqual(1 + 2 + 14, sum);//重构 int sum = calculator.Add(stringNumbers); Assert.AreEqual(expected, sum); } //需求7:字符串中包括负数将抛异常 [TestMethod] [DataRow(1 + 2 + 3 + 11, "//;\n1;-2\n3;11")] [ExpectedException(typeof(ArgumentException),"参数字符串里不允许有负数。")] public void Add_IfNegativeNumbersAreUsed_ThrowException(int expected, string stringNumbers) { StringCalculator calculator = new StringCalculator(); int sum = calculator.Add(stringNumbers); Assert.AreEqual(expected, sum); } //需求8:字符串中数了超过1000应过滤掉。 [TestMethod] [DataRow(1 + 2 + 3+1000, "//;\n1;2\n3;1000;1005")] [DataRow(1 + 2 + 3, "//;\n1;2\n3;1001")] public void Add_IfNumbersAreGreaterThan1000_IgnoreThoseNumbers(int expected, string stringNumbers) { StringCalculator calculator = new StringCalculator(); int sum = calculator.Add(stringNumbers); Assert.AreEqual(expected, sum); } //需求9:分隔符可以是任意长度的字符串。 //[##]\n1##3##6 //[TestMethod] //[DataRow(1 + 2 + 3 + 1000, "//[##]\n1##2\n3##1000##1005")] //[DataRow(1 + 2 + 3 + 1000, "//[#!#]\n1#!#2\n3#!#1000#!#1005")] //public void Add_ShouldSupportAnyLengthOfDelimiterString(int expected, string stringNumbers) //{ // StringCalculator calculator = new StringCalculator(); // int sum = calculator.Add(stringNumbers); // Assert.AreEqual(expected, sum); //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringProcessor { public class StringCalculator { public int Add(string numbers) { int sum = 0; var delimiters = new string[] { ",", "\n" }; //需求6:支持不同的分隔符,//[分隔符]\n数字 //;\n1;2;4 if (numbers.StartsWith("//")) { var newDelimiter = numbers[2].ToString(); //var newDelimiter = GetDelimiters(numbers);//需求9:分隔符可以是任意长度的字符串。 //[##]\n1##3##6 var s = new string[] { newDelimiter }; Array.Resize(ref delimiters, delimiters.Length + 1);//需求6 delimiters[delimiters.Length - 1] = newDelimiter; //需求6 numbers = numbers.Substring(3); //numbers = numbers.Substring(numbers.IndexOf(']') +1);//需求9:分隔符可以是任意长度的字符串。 //[##]\n1##3##6 } String[] numbersArray = numbers.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); //if(numbersArray.Length > 2)// //需求4:允许接收不固定数字个数的字符串。 //{ // throw new ArgumentException("参数应该是不能超过2个数字且用逗号‘,’分隔的字符串。"); //} //else //{ foreach (var number in numbersArray) { if (!string.IsNullOrEmpty(number))//added when fix step1/step2 failed test { var intNumber = Convert.ToInt16(number); if (intNumber < 0)//需求7:字符串中包括负数将抛异常 { throw new ArgumentException("参数字符串里不允许有负数。");//需求7:字符串中包括负数将抛异常 } if (intNumber <= 1000)//需求8:字符串中数了超过1000应过滤掉。 { sum += intNumber; } } } //} return sum; } //需求9:分隔符可以是任意长度的字符串。 //[##]\n1##3##6 private string GetDelimiters(string stringNumbers) { var leftSquareBracketIndex = stringNumbers.IndexOf('['); var rightSquareBracketIndex = stringNumbers.IndexOf(']'); var delimiterStartIndex = leftSquareBracketIndex + 1; var delimiterLength = rightSquareBracketIndex - leftSquareBracketIndex - 1; return stringNumbers.Substring(delimiterStartIndex, delimiterLength); } //public int AddNumbers(string args) //{ // if (string.IsNullOrEmpty(args)) // { // return 0; // } // var delimeters = new List<char>() // { // '\n',',' // }; // if (args[0] == '/') // { // var customDelimeter = args[2]; // delimeters.Add(customDelimeter); // args = args.Remove(0, // 3); // } // var numbers = args.ToCharArray().Where(x => !delimeters.Contains(x)).ToList(); // if (numbers.Any(x => x == '-')) // { // StringBuilder stringBuilder = new StringBuilder(); // for (int i = 0; // i < numbers.Count; // i++) // { // if (numbers[i] == '-') // { // stringBuilder.Append("-"); // stringBuilder.Append(numbers[++i]); // stringBuilder.Append(", "); // } // } // throw new Exception(string.Format("negatives {0} not allowed", stringBuilder.ToString())); // } // var sum = numbers.Sum(x => (int)Char.GetNumericValue(x)); // return sum; //} } }
b114e7e654ae2e6e43411623226cb951f3a6d8df
[ "C#" ]
2
C#
richardyang-gdc/StringCalculator
f86e0f400223632ee71210b35f6789c4d42e9671
c15857a393cfb643088a1118f276c35c5bfab11e
refs/heads/master
<repo_name>Spin42/pp-scoreboard<file_sep>/ping_pong.rb require "json" class PingPong attr_accessor :users, :games def initialize load_users load_games end def find_user_by_name(name) # Improve this, must be in one line :) found_users = @users.select do |user| user["name"] == name end found_users[0] end def find_user_by_id(id) # Improve this, must be in one line :) found_users = @users.select do |user| user["id"] == id end found_users[0] end def add_game(player1, player2, score_player1, score_player2) @games << { "player_id1" => player1["id"], "player_id2" => player2["id"], "score_player1" => score_player1, "score_player2" => score_player2 } save_games end def add_user(name) if !find_user(name) @users << { "id" => @users.size + 1, "name" => name } save_users end end def display_games @games.each do |game| player1_name = find_user_by_id(game["player_id1"])["name"] player2_name = find_user_by_id(game["player_id2"])["name"] puts "#{player1_name} - #{game["score_player1"]}" puts "#{player2_name} - #{game["score_player2"]}" puts "***** END OF GAME *****" end end private def load_users File.open("./users.json", "r") do |file| @users = JSON.parse(file.read) end end def load_games File.open("./games.json", "r") do |file| @games = JSON.parse(file.read) end end def save_users File.open("./users.json", "w") do |file| file.write(JSON.generate(@users)) end end def save_games File.open("./games.json", "w") do |file| file.write(JSON.generate(@games)) end end end ping_pong = PingPong.new ping_pong.display_games # ping_pong.add_user("Pierre") # ping_pong.add_user("Gonzalo") # player1 = ping_pong.find_user("Pierre") # player2 = ping_pong.find_user("Gonzalo") # ping_pong.add_game(player1, player2, 21, 17)
74a983c041eddaadcda7b603766748463f7c4e91
[ "Ruby" ]
1
Ruby
Spin42/pp-scoreboard
c4d14756d2e86bf5bb0ef55ef173e03ee2cdba8c
a1c7a35ba24e3a07107ce72ee8f9cfdae6ad2977
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebScheduler.Models { public class AdaptedModels { } }<file_sep>using System; using System.Linq; using System.Web; using WebScheduler.Models; using WebMatrix.WebData; namespace WebScheduler.Filters { public class LocalizedStringsManager { static Entities db = new Entities(); int culture; static LocalizedStringsManager instance; public string Lang { get { return (from lang in db.Langs where lang.Id == this.culture select lang.Name).First(); } } public static string StaticLang { get { return instance.Lang; } } public static bool IsInitialized { get { return instance != null; } } public static LocalizedStringsManager GetInstance() { if (instance == null) throw new InvalidOperationException(); return instance; } public static void Initialize(HttpRequestBase request) { if (request.IsAuthenticated) instance = new LocalizedStringsManager((from user in db.UserData where user.UserId == WebSecurity.CurrentUserId select user.LangId).First()); else if (request.Cookies["lang"] != null) instance = new LocalizedStringsManager(request.Cookies["lang"].Value); else throw new InvalidOperationException(); } public static void Initialize(string lang) { instance = new LocalizedStringsManager(lang); } private LocalizedStringsManager(string culture) { this.culture = (from lang in db.Langs where lang.Name == culture select lang.Id).First(); } private LocalizedStringsManager(int culture) { this.culture = culture; } public string this[string key] { get { return (from str in db.StringsLocalization where str.LangId == culture && str.StringNames.Name == key select str.LocalizedString).First(); } set { StringsLocalization str = new StringsLocalization() { LangId = culture, StringNames = (from name in db.StringNames where name.Name == key select name).First() ?? new StringNames() { Name = key }, LocalizedString = value }; db.StringsLocalization.Add(str); db.SaveChanges(); } } } }<file_sep>function addUserProperty() { var counter = 0; while ($("#additionalUserData #additionalUserData" + counter).length != 0) counter++; $("#additionalUserData").append("<div id=\"additionalUserData" + counter + "\">" + "<div id=\"userdata-name" + counter + "\" class=\"userdata-name\">" + "<input class=\"text-box single-line\" id=\"UserProperties_" + counter + "__Name\" name=\"UserProperties[" + counter + "].Name\" type=\"text\" value=\"\">" + "<span class=\"field-validation-valid\" data-valmsg-for=\"UserProperties[" + counter + "].Name\" data-valmsg-replace=\"true\"></span>" + "</div>" + "<div id=\"userdata-value" + counter + "\" class=\"userdata-value\">" + "<input class=\"text-box single-line\" id=\"UserProperties_" + counter + "__Value\" name=\"UserProperties[" + counter + "].Value\" type=\"text\" value=\"\">" + "<span class=\"field-validation-valid\" data-valmsg-for=\"UserProperties[" + counter + "].Value\" data-valmsg-replace=\"true\"></span>" + "</div>" + "<div id=\"delete-userdata" + counter + "\" class=\"delete-userdata\">" + "<a href=\"javascript:deleteUserProperty(" + counter + ")\">DeleteUserProperty</a>" + "</div>" + "</div>"); normalizeProperties(); } function deleteUserProperty(target) { $("#additionalUserData" + target).remove(); normalizeProperties(); } function normalizeProperties() { var images = $("#additionalUserData ").children(); var counter = images.length; for (var i = 0; i < images.length; i++) { $(images[i]).attr("id", "additionalUserData" + i); $(images[i]).children("[id^=UserProperties][id$=UserId]").attr("name", "UserProperties[" + i + "].UserId"); $(images[i]).children("[id^=UserProperties][id$=UserId]").attr("id", "UserProperties_" + i + "__UserId"); $(images[i]).children("[id^=UserProperties][id$=_Id]").attr("name", "UserProperties[" + i + "].Id"); $(images[i]).children("[id^=UserProperties][id$=_Id]").attr("id", "UserProperties_" + i + "__Id"); var obj = $(images[i]).children("[id^=userdata-name]"); obj.attr("id", "userdata-name" + i); obj.children(".field-validation-valid").attr("data-valmsg-for", "UserProperties[" + i + "].Name"); var obj1 = obj.children("[id^=UserProperties_]"); obj1.attr("id", "UserProperties_" + i + "__Name"); obj1.attr("name", "UserProperties[" + i + "].Name"); obj = $(images[i]).children("[id^=userdata-value]"); obj.attr("id", "userdata-value" + i); obj.children(".field-validation-valid").attr("data-valmsg-for", "UserProperties[" + i + "].Value"); obj1 = obj.children("[id^=UserProperties_]"); obj1.attr("id", "UserProperties_" + i + "__Value"); obj1.attr("name", "UserProperties[" + i + "].Value"); $(images[i]).children(".delete-userdata").children("a").attr("href", "javascript:deleteUserProperty(" + i + ")"); $(images[i]).children(".delete-userdata").attr("id", "delete-userdata" + i); } }<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; using WebMatrix.WebData; using WebScheduler.Filters; namespace WebScheduler.Models { public class UserDataViewModel { public UserDataViewModel() { } public UserDataViewModel(int id) : this((from users in (new Entities()).UserData where users.UserId == WebSecurity.CurrentUserId select users).First()) { } public UserDataViewModel(UserData source) { this.UserId = source.UserId; this.UserProperties = source.UserProperties.ToList(); this.Name = source.Name; this.Surname = source.Surname; this.SecondName = source.SecondName; this.BirthDate = source.BirthDate; this.PictureId = source.PictureId; //this.Picture = (new MemoryStream(source.Picture)); } public int UserId { get; set; } public string Name { get; set; } public string Surname { get; set; } public string SecondName { get; set; } public Nullable<System.DateTime> BirthDate { get; set; } public int? PictureId { get; set; } [ValidateImage(ErrorMessage = "Image must be less than 1 MB and have format png, jpeg or gif.")] public HttpPostedFileBase Picture { get; set; } public int LangId { get; set; } public List<UserProperties> UserProperties { get; set; } public UserData ToUserData() { UserData userdata = new UserData { UserId = this.UserId, Name = this.Name, Surname = this.Surname, SecondName = this.SecondName, BirthDate = this.BirthDate, LangId = this.LangId, }; if (this.UserProperties != null) userdata.UserProperties = (from property in this.UserProperties where property.Name != null && property.Value !=null select property).ToList(); if (Picture != null) { MemoryStream ms = new MemoryStream(); Image img = Image.FromStream(this.Picture.InputStream); img.Save(ms, img.RawFormat); userdata.Images = new Images { Image = ms.ToArray() }; } return userdata; } } }<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using WebScheduler.Classes; using WebScheduler.Models; namespace WebScheduler.Controllers { public class PictureController : Controller { Entities db = new Entities(); // // GET: /Picture/Index/1232134 public ActionResult Index(string id) { byte[] image = db.Images.Find(ImageHelper.GetImageHash(int.Parse(id))).Image; MemoryStream ms = new MemoryStream(image); string format; if (Image.FromStream(ms).RawFormat == ImageFormat.Gif) format = "image/gif"; else if (Image.FromStream(ms).RawFormat == ImageFormat.Jpeg) format = "image/jpeg"; else if (Image.FromStream(ms).RawFormat == ImageFormat.Png) format = "image/png"; else format = "image/jpeg"; return base.File(image, format); } } } <file_sep>using System; using System.Web; using System.Web.Mvc; namespace WebScheduler.Filters { [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class InitializeLocaleManagerAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //LocalizedStringsManager.Initialize(filterContext.HttpContext.Request); try { LocalizedStringsManager.Initialize(filterContext.HttpContext.Request); } catch (Exception) { filterContext.HttpContext.Response.Cookies.Add(new HttpCookie("lang", "en") { Path = "/*" }); LocalizedStringsManager.Initialize("en"); } } } }<file_sep>webscheduler ============ Project for webchallenge. It should be something like google calendar but it was not completely as it was done actually for 4 days :P I want to use it as a platform for organizer suitable for me. With some removed and some added features. And in form of one or two SPAs. Project uses aspnet mvc 4. Can be easily built and run with Visual Studio 2010 or newer. <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebScheduler.Classes { public static class ImageHelper { public static int? GetImageHash(int? id) { return id ^ 1541014539; } public static IHtmlString Picture(this HtmlHelper Html, int? id, string alt) { return Html.Raw(String.Format("<img src=\"/Picture/Index/{0}\" alt=\"{1}\">",GetImageHash(id),alt)); } } }
cdf6888f6937cadbe5733b91f3ef2859f56a6d85
[ "JavaScript", "C#", "Markdown" ]
8
C#
koskokos/webscheduler
97b4528f59cb09990e42844908e673d802f95cc6
488a596b7619db0620011cef0bfdbbd3ab7b1819
refs/heads/master
<repo_name>BruceDaMoose/politinder-1<file_sep>/pt.sql -- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Host: localhost:8889 -- Generation Time: May 19, 2017 at 12:54 PM -- Server version: 5.6.35 -- PHP Version: 7.0.15 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `pt` -- -- -------------------------------------------------------- -- -- Table structure for table `evnt` -- CREATE TABLE `evnt` ( `e_id` int(11) NOT NULL, `date` varchar(45) DEFAULT NULL, `clock` varchar(45) DEFAULT NULL, `Fk_p_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `keyissue` -- CREATE TABLE `keyissue` ( `ki_id` int(11) NOT NULL, `issue` varchar(200) DEFAULT NULL, `description` text ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `news` -- CREATE TABLE `news` ( `n_id` int(11) NOT NULL, `name` varchar(45) DEFAULT NULL, `phonenb` varchar(45) DEFAULT NULL, `town_n` varchar(45) DEFAULT NULL, `Fk_e_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `politiker` -- CREATE TABLE `politiker` ( `p_id` int(11) NOT NULL, `name` varchar(100) DEFAULT NULL, `town` varchar(50) DEFAULT NULL, `Fk_ki_id` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Indexes for dumped tables -- -- -- Indexes for table `evnt` -- ALTER TABLE `evnt` ADD PRIMARY KEY (`e_id`), ADD KEY `Fk_p_id_idx` (`Fk_p_id`); -- -- Indexes for table `keyissue` -- ALTER TABLE `keyissue` ADD PRIMARY KEY (`ki_id`); -- -- Indexes for table `news` -- ALTER TABLE `news` ADD PRIMARY KEY (`n_id`), ADD KEY `Fk_e_id_idx` (`Fk_e_id`); -- -- Indexes for table `politiker` -- ALTER TABLE `politiker` ADD PRIMARY KEY (`p_id`), ADD KEY `Fk_ki_id_idx` (`Fk_ki_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `evnt` -- ALTER TABLE `evnt` MODIFY `e_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `keyissue` -- ALTER TABLE `keyissue` MODIFY `ki_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `news` -- ALTER TABLE `news` MODIFY `n_id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `politiker` -- ALTER TABLE `politiker` MODIFY `p_id` int(11) NOT NULL AUTO_INCREMENT; -- -- Constraints for dumped tables -- -- -- Constraints for table `evnt` -- ALTER TABLE `evnt` ADD CONSTRAINT `Fk_p_id` FOREIGN KEY (`Fk_p_id`) REFERENCES `politiker` (`p_id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `news` -- ALTER TABLE `news` ADD CONSTRAINT `Fk_e_id` FOREIGN KEY (`Fk_e_id`) REFERENCES `evnt` (`e_id`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Constraints for table `politiker` -- ALTER TABLE `politiker` ADD CONSTRAINT `Fk_ki_id` FOREIGN KEY (`Fk_ki_id`) REFERENCES `keyissue` (`ki_id`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
a18029b35e2ee46f079cdbeb8ed51e75df5201b9
[ "SQL" ]
1
SQL
BruceDaMoose/politinder-1
11ad7039d76746e763ea6c215b6a9549ddfd4d1b
5cbcec64d4f9868ce6872d74a142ca686b808e4f
refs/heads/master
<file_sep>#!/usr/bin/env python from heroprotocol.mpyq import mpyq from heroprotocol import protocol29406 import argparse import datetime import sys from pprint import pprint def loop2dur(loops): # 16 gameloops per second seconds = loops / 16 mins = seconds / 60 secs = seconds % 60 timestring = "" if mins > 0: timestring = "%02dm" % mins timestring += "%02ds" % secs return {'sec': seconds, 'duration': { 'min': mins, 'sec': secs, 'string': timestring }} parser = argparse.ArgumentParser() parser.add_argument('replay_file', help='.SC2Replay file to load') args = parser.parse_args() archive = mpyq.MPQArchive(args.replay_file) contents = archive.header['user_data_header']['content'] header = protocol29406.decode_replay_header(contents) # The header's baseBuild determines which protocol to use baseBuild = header['m_version']['m_baseBuild'] try: protocol_name = 'protocol%s' % (baseBuild,) protocols = __import__('heroprotocol', globals(), locals(), [protocol_name]) protocol = getattr(protocols, protocol_name) except Exception as e: print >> sys.stderr, 'Unsupported base build: %d, %s' % (baseBuild, e) sys.exit(1) contents = archive.read_file('replay.details') details = protocol.decode_replay_details(contents) contents = archive.read_file('replay.initData') initdata = protocol.decode_replay_initdata(contents) contents = archive.read_file('replay.message.events') messages = protocol.decode_replay_message_events(contents) game_options = initdata['m_syncLobbyState']['m_gameDescription']['m_gameOptions'] lobby_state = initdata['m_syncLobbyState']['m_lobbyState'] print details['m_title'] print "Elapsed time: %s (%d)" % (loop2dur(header['m_elapsedGameLoops'])['duration']['string'], header['m_elapsedGameLoops']) print "RNGesus says: %s" % (lobby_state['m_randomSeed']) if game_options['m_competitive']: print "<competative game>" if game_options['m_cooperative']: print "<coop game>" for player_state in lobby_state['m_slots']: print "%s/%s (%s): %s[%s] (%s) rewards: %s" % (player_state['m_teamId'], player_state['m_userId'], player_state['m_toonHandle'], player_state['m_hero'], player_state['m_skin'], player_state['m_mount'], len(player_state['m_rewards'])) for player in details['m_playerList']: print "%d: %s (%s) [playerId: %d]" % (player['m_teamId'], player['m_hero'], player['m_name'], player['m_toon']['m_id']) for message in messages: duration = loop2dur(message['_gameloop']) if message['_event'] == 'NNet.Game.SPingMessage': if message['m_recipient'] == 1: target = 'all' else: target = 'allies? (%s)' % (message['m_recipient']) player_name = details['m_playerList'][message['_userid']['m_userId']]['m_name'] print "%s: #%s [%s] PING (%s, %s)" % (duration['duration']['string'], target, player_name, message['m_point']['x'], message['m_point']['y']) elif message['_event'] == 'NNet.Game.SChatMessage': if message['m_recipient'] == 1: target = 'all' else: target = 'allies? (%s)' % (message['m_recipient']) player_name = details['m_playerList'][message['_userid']['m_userId']]['m_name'] print "%s: #%s <%s> %s" % (duration['duration']['string'], target, player_name, message['m_string']) <file_sep># What Dumping some data via offical HoTS replay lib from Blizzard # Howto python info.py "replays/Dragon Shire.StormReplay" If it complains protocol version not supported you can try and update the submodule for the heroprotocol repo. If no new protocols are added by Blizzard you can probably copy the highest protocol number file from heroprotocol/protocol39445.py (currently highest) to the latest version number heroprotocol/protocol39709.py (currently) and it will work (unless they changed the protocol which they only seem to do every 5-10 versions (probably when new heroes are added).
5650bf05bcb3a0a13cdc53cad41da846f8f6a279
[ "Markdown", "Python" ]
2
Python
simeng/heroproject
c0c2d0538fd932e0c8df88978739b35e6095e507
45a0cae1aef7cdb841b664dad0ce52f91546d319
refs/heads/master
<repo_name>Bingrong89/DOF6_Python<file_sep>/dof6.py """Python 3.7, OpenCV 4.1.1""" import os import sys import math import argparse import numpy as np import cv2 from cv2 import FileStorage from six_dof_functions import * parser = argparse.ArgumentParser('Input video, .yml and .ply file names in' ' same directory or absolute paths ' '\nWhile video is playing: ' '\n Press ESC to exit' '\n Press s to pause or resume\n' ) parser.add_argument('--video',type=str,help='Input video file', default='box.mp4') parser.add_argument('--yml',type=str,help='Input yml file', default='cookies_ORB.yml') parser.add_argument('--ply',type=str,help='Input ply file', default='box.ply') # Camera calibration matrix FOCALLENGTH = 55. SENSOR_X = 22.3 SENSOR_Y = 14.9 WIDTH = 640 HEIGHT = 480 calibration_matrix = np.zeros((3,3),dtype=np.float64) calibration_matrix[0,0] = WIDTH*FOCALLENGTH / SENSOR_X #FX calibration_matrix[1,1] = HEIGHT*FOCALLENGTH / SENSOR_Y #FY calibration_matrix[0,2] = WIDTH/2 #CX calibration_matrix[1,2] = HEIGHT/2 #CY calibration_matrix[2,2] = 1 # Ratio test RATIO_TEST_THRESHOLD = 0.8 # SolvePnpRansac parameters iterationsCount = 500 reprojectionError = 6.0 #2.0 confidence = 0.99 #0.95 # Kalman Filter initialization parameters KF_N_STATES = 18 KF_N_MEASUREMENTS = 6 KF_N_INPUTS = 0 KF_DT = 0.125 #Inlier condition for triggering usage of measured and update KF with measured. MIN_INLIERS_KALMAN = 30 KF = initKalmanFilter(KF_N_STATES,KF_N_MEASUREMENTS,KF_N_INPUTS,KF_DT) # Create matcher """ FLANN_INDEX_LSH = 6 index_params= dict(algorithm = FLANN_INDEX_LSH, table_number = 6, # 12 key_size = 12, # 20 multi_probe_level = 1) #2 search_params = dict(checks=50) matcher = cv2.FlannBasedMatcher(index_params, search_params) """ matcher = cv2.BFMatcher_create(normType=cv2.NORM_HAMMING) # Feature detector orb = cv2.ORB_create(nfeatures=2000) def image_2_6dof(color_img,model_points3d,model_descriptors, mesh_vertices,mesh_triangles): """ Input: Raw color image Output: Color image with mesh and axes drawn """ # Get ORB features and descriptors from input img. img = cv2.cvtColor(color_img,cv2.COLOR_BGR2GRAY) img_keypoints = orb.detect(img) img_keypoints, img_descriptors = orb.compute(img,img_keypoints) # Match input img ORB descriptors with model descriptors. match12 = matcher.knnMatch(img_descriptors,model_descriptors,2) match21 = matcher.knnMatch(model_descriptors,img_descriptors,2) # This is the block from robustMatch, fast version is not implemented. removed1 = ratiotest(match12,RATIO_TEST_THRESHOLD) removed2 = ratiotest(match21,RATIO_TEST_THRESHOLD) good_matches = symmetry_test(removed1,removed2) for row in removed1: good_matches.append([row[0].queryIdx,row[0].trainIdx,row[0].distance]) points3d_model_match = [] points2d_scene_match = [] for x in range(len(good_matches)): point3d_model = model_points3d[good_matches[x][1]] #1 for trainidx points3d_model_match.append(point3d_model) points2d_scene = img_keypoints[good_matches[x][0]].pt #0 for queryidx points2d_scene_match.append(points2d_scene) draw_2d_points(color_img,points2d_scene_match,(0,0,200)) # Pose estimation with PnP and Ransac, main function: cv2.solvePnPRansac. measurements = np.zeros((KF_N_MEASUREMENTS,1)) good_measurement = False projection_to_use = None color = None list_2dpoints_inliers = [] if len(good_matches) >=4: rotation_matrix,translation_matrix,projection_matrix,inliers, retval\ = estimatePoseRANSAC(np.array(points3d_model_match), np.array(points2d_scene_match), calibration_matrix, cv2.SOLVEPNP_EPNP, np.empty(0), iterationsCount, reprojectionError,confidence) if inliers.shape[0]>0 and retval: for inlier in inliers: list_2dpoints_inliers.append(points2d_scene_match[inlier.item()]) draw_2d_points(color_img,list_2dpoints_inliers,(200,0,0)) if len(inliers) >=MIN_INLIERS_KALMAN: measurements = fillMeasurements(translation_matrix, rotation_matrix, KF_N_MEASUREMENTS) good_measurement = True translation_estimated, rotation_estimated = update_KF(KF,measurements) if not good_measurement: """ If this block executes before KF is ever updated with nonzero measurements,calling drawobjectMesh might result in script crashing due to division by zero inside backproject3dPoint at the normalization step. """ projection_to_use = get_projection_matrix(rotation_estimated, translation_estimated) color = (255,0,0) else: projection_to_use = projection_matrix color = (0,255,0) # Draw object mesh based on selected projection matrix. drawObjectMesh(color_img,mesh_vertices,mesh_triangles, calibration_matrix,projection_to_use,color) # Draw the cartesian axes arrows on the predicted pose. draw_3d_axes(color_img,projection_to_use,calibration_matrix) # Cannot use cv2.solvePnPRansac if less than 4 in good_matches, just skip. else: pass return color_img def factory(video_file,model_points3d,model_descriptors, mesh_vertices,mesh_triangles): """ Main function, handles the non image processing stuff. """ video = cv2.VideoCapture(video_file) while (video.isOpened()): ret,frame = video.read() if not ret: break dof_img = image_2_6dof(frame,model_points3d,model_descriptors, mesh_vertices,mesh_triangles) cv2.imshow('6 DOF',dof_img) key = cv2.waitKey(100) if key == 27: #Esc key cv2.destroyAllWindows() print("Terminating video") sys.exit() elif key == ord('s'): print("Pausing video") while True: key2 = cv2.waitKey(1) if key2 == ord('s'): print("Resuming video") break if key2 == 27: cv2.destroyAllWindows() print("Terminating video") sys.exit() else: continue print("End of video") if __name__ == '__main__': args = parser.parse_args() video_file = args.video yml_file = args.yml ply_file = args.ply # Read yml file, FileStorage class documentation link below # https://docs.opencv.org/master/da/d56/classcv_1_1FileStorage.html fs_storage = FileStorage(yml_file,0) model_points3d = fs_storage.getNode('points_3d').mat() model_descriptors = fs_storage.getNode('descriptors').mat() # Read from ply file mesh_vertices,mesh_triangles = read_ply(ply_file) factory(video_file,model_points3d,model_descriptors, mesh_vertices,mesh_triangles) <file_sep>/six_dof_functions.py import math import numpy as np import cv2 def read_ply(plyfilepath): # Open the ply file and extract relevant data. vertex_list = [] triangle_list = [] ply_obj = open(plyfilepath,'r') end_header = False vertex_count = 0 for line in ply_obj: if end_header == False: if 'element vertex' in line: vertex_total = line.strip().split(' ')[-1] assert vertex_total.isdigit(),\ 'vertex_count value not positive integer!' if 'element face' in line: triangle_total = line.strip().split(' ')[-1] assert triangle_total.isdigit(),\ 'triangle_count value not integer!' if 'end_header' in line: end_header = True elif end_header == True: if vertex_count != int(vertex_total): vertex_list.append(line.strip().split()) vertex_count +=1 else: triangle_list.append(line.strip().split()[1:]) ply_obj.close() return vertex_list, triangle_list def ratiotest(knnmatch_output,threshold=0.8): newlist = [] for pair in knnmatch_output: if len(pair) !=2: continue dist1 = pair[0].distance dist2 = pair[1].distance ratio = dist1/dist2 if ratio < threshold: newlist.append(pair) return newlist def symmetry_test(array1,array2): symmatch = [] for pair1 in array1: for pair2 in array2: if (pair1[0].queryIdx == pair2[0].trainIdx) and\ (pair2[0].queryIdx == pair1[0].trainIdx): symmatch.append([pair1[0].queryIdx, pair1[0].trainIdx, pair1[0].distance]) break return symmatch def draw_2d_points(img,points_list,color): for point in points_list: cv2.circle(img,(int(point[0]),int(point[1])),4,color,-1,8) def get_projection_matrix(rotation_matrix,translation_matrix): projection_matrix = np.zeros((3,4)) projection_matrix[:3,:3] = rotation_matrix projection_matrix[:,3] = translation_matrix[:,0] return projection_matrix def estimatePoseRANSAC(list_points3d,list_points2d,calibration_matrix,flags, inliers,iterationscount,reprojectionerror,confidence): distCoeffs = np.zeros((4,1)) output_rot_vec = np.zeros((3,1)) output_trans_vec = np.zeros((3,1)) useExtrinsicguess = False # SolvePnPRansac documentation link below # https://docs.opencv.org/master/d9/d0c/group__calib3d.html#ga50620f0e26e02caa2e9adc07b5fbf24e retval, output_rot_vec, output_trans_vec, inliers =\ cv2.solvePnPRansac(list_points3d,list_points2d,calibration_matrix,None, flags=flags,iterationsCount=iterationscount) rotation_matrix = np.zeros((3,3)) rotation_matrix,_ = cv2.Rodrigues(output_rot_vec,rotation_matrix) translation_matrix = output_trans_vec projection_matrix = get_projection_matrix(rotation_matrix, translation_matrix) if inliers is None: inliers = np.empty(0) return rotation_matrix, translation_matrix, \ projection_matrix, inliers, retval def backproject3dPoint(point3d,calibration_matrix,projection_matrix): """ Explictly use np.matmul to ensure conventional matrix multiplication even if python lists are used to represent the arrays. """ step_one = np.matmul(calibration_matrix,projection_matrix) # Shape(3,4) step_two = np.matmul(step_one,point3d) # Shape(3,1) # Normalization x_coord = step_two[0] / step_two[2] y_coord = step_two[1] / step_two[2] return (x_coord,y_coord) def initKalmanFilter(n_states,n_measurements,n_inputs,dt): KF = cv2.KalmanFilter(n_states,n_measurements,n_inputs,cv2.CV_64F) KF.processNoiseCov = cv2.setIdentity(KF.processNoiseCov,1e-5) KF.measurementNoiseCov = cv2.setIdentity(KF.measurementNoiseCov,1e-2) KF.errorCovPost = cv2.setIdentity(KF.errorCovPost,1) dt_2 = 0.5*(dt**2) """ Problem: Assigning directly to elements in KF.transitionMatrix and KF.measurementMatrix through numpy indexing does not actually change the underlying data when calling them. Quick solution: Reassign the variable directly to a new array object. """ tempTM = KF.transitionMatrix tempMM = KF.measurementMatrix # Position tempTM[0,3] = dt tempTM[1,4] = dt tempTM[2,5] = dt tempTM[3,6] = dt tempTM[4,7] = dt tempTM[5,8] = dt tempTM[0,6] = dt_2 tempTM[1,7] = dt_2 tempTM[2,8] = dt_2 # Orientation tempTM[9,12] = dt tempTM[10,13] = dt tempTM[11,14] = dt tempTM[12,15] = dt tempTM[13,16] = dt tempTM[14,17] = dt tempTM[9,15] = dt_2 tempTM[10,16] = dt_2 tempTM[11,17] = dt_2 tempMM[0,0] = 1 # X tempMM[1,1] = 1 # Y tempMM[2,2] = 1 # Z tempMM[3,9] = 1 # Roll tempMM[4,10] = 1 # Pitch tempMM[5,11] = 1 # Yaw KF.transitionMatrix = tempTM KF.measurementMatrix = tempMM return KF def update_KF(KF,measurement): # Update Kalman filter with good measurements. prediction = KF.predict() estimated = KF.correct(measurement) translation_estimated = np.empty((3,1),dtype=np.float64) translation_estimated[0] = estimated[0] translation_estimated[1] = estimated[1] translation_estimated[2] = estimated[2] eulers_estimated = np.empty((3,1),dtype=np.float64) eulers_estimated[0] = estimated[9] eulers_estimated[1] = estimated[10] eulers_estimated[2] = estimated[11] rotation_estimated = euler2rot(eulers_estimated) return translation_estimated,rotation_estimated def rot2euler(rot_mat): # From Utils.cpp, cv::Mat rot2euler(const cv::Mat & rotationMatrix). euler = np.empty((3,1),dtype=np.float64) m00 = rot_mat[0,0] m02 = rot_mat[0,2] m10 = rot_mat[1,0] m11 = rot_mat[1,1] m12 = rot_mat[1,2] m20 = rot_mat[2,0] m22 = rot_mat[2,2] bank = None attitude= None heading = None if m10 > 0.998: bank = 0 attitude = math.pi/2 heading = math.atan2(m02,m22) elif m10 <-0.998: bank = 0 attitude = -math.pi/2 heading = math.atan2(m02,m22) else: bank = math.atan2(-m12,m11) attitude = math.asin(m10) heading = math.atan2(-m20,m00) euler[0] = bank euler[1] = attitude euler[2] = heading return euler def euler2rot(euler): # From Utils.cpp, cv::Mat euler2rot(const cv::Mat & euler). rot_mat = np.empty((3,3),dtype=np.float64) bank = euler[0] attitude = euler[1] heading = euler[2] ch = math.cos(heading) sh = math.sin(heading) ca = math.cos(attitude) sa = math.sin(attitude) cb = math.cos(bank) sb = math.sin(bank) m00 = ch * ca m01 = (sh*sb) - (ch*sa*cb) m02 = (ch*sa*sb) + (sh*cb) m10 = sa m11 = ca * cb m12 = -ca * sb m20 = -sh * ca m21 = (sh*sa*cb) + (ch*sb) m22 = -(sh*sa*sb) + (ch*cb) rot_mat[0,0] = m00 rot_mat[0,1] = m01 rot_mat[0,2] = m02 rot_mat[1,0] = m10 rot_mat[1,1] = m11 rot_mat[1,2] = m12 rot_mat[2,0] = m20 rot_mat[2,1] = m21 rot_mat[2,2] = m22 return rot_mat def fillMeasurements(translation_matrix,rotation_matrix,n_measurements): """ Accurately speaking, it is creating here, not filling. Leaving the name as is to make it easier to trace back to the original C++ implementation. """ measurements = np.zeros((n_measurements,1),dtype=np.float64) measured_eulers = rot2euler(rotation_matrix) measurements[0] = translation_matrix[0] # X measurements[1] = translation_matrix[1] # Y measurements[2] = translation_matrix[2] # Z measurements[3] = measured_eulers[0] # Roll measurements[4] = measured_eulers[1] # Pitch measurements[5] = measured_eulers[2] # Yaw return measurements def drawObjectMesh(img, vertices,triangles,calib_mat, proj_mat,col=(255,100,100)): for triangle in triangles: point_3d_0 = vertices[int(triangle[0])][:] point_3d_1 = vertices[int(triangle[1])][:] point_3d_2 = vertices[int(triangle[2])][:] # PnpProblem.cpp line 171, appending string here since triangles # are loaded as arrays of strings representing integers. point_3d_0.append('1') point_3d_1.append('1') point_3d_2.append('1') point_3d_0 = np.array(point_3d_0,dtype='float').reshape(4,1) point_3d_1 = np.array(point_3d_1,dtype='float').reshape(4,1) point_3d_2 = np.array(point_3d_2,dtype='float').reshape(4,1) point_2d_0 = backproject3dPoint(point_3d_0,calib_mat,proj_mat) point_2d_1 = backproject3dPoint(point_3d_1,calib_mat,proj_mat) point_2d_2 = backproject3dPoint(point_3d_2,calib_mat,proj_mat) # cv2.line changes the image object by reference. _ = cv2.line(img,point_2d_0,point_2d_1,col,2) _ = cv2.line(img,point_2d_1,point_2d_2,col,2) _ = cv2.line(img,point_2d_2,point_2d_0,col,2) def drawArrow(img, tail, head, color, arrow_size,thickness=20): cv2.line(img,tail,head,color,thickness) # Indices 0 1 2 represent Axes X Y Z respectively. angle = math.atan2(tail[1] - head[1] ,tail[0] - head[0]) # First segment value_one = int(head[0] + (arrow_size*math.cos(angle + (math.pi/4)))) value_two = int(head[1] + (arrow_size*math.sin(angle + (math.pi/4)))) cv2.line(img,(value_one,value_two),head,color,thickness) # Second segment, same as first but sign flip inside the trigo argument. value_one = int(head[0] + (arrow_size*math.cos(angle - (math.pi/4)))) value_two = int(head[1] + (arrow_size*math.sin(angle - (math.pi/4)))) cv2.line(img,(value_one,value_two),head,color,thickness) def draw_3d_axes(img,projection_to_use,calib_mat): X = 5 origin = backproject3dPoint(np.array([[0],[0],[0],[1]]), calib_mat,projection_to_use) x_axis = backproject3dPoint(np.array([[X],[0],[0],[1]]), calib_mat,projection_to_use) y_axis = backproject3dPoint(np.array([[0],[X],[0],[1]]), calib_mat,projection_to_use) z_axis = backproject3dPoint(np.array([[0],[0],[X],[1]]), calib_mat,projection_to_use) red = (0,0,255) yellow = (0,255,255) blue = (255,0,0) black = (0,0,0) drawArrow(img,origin,x_axis,red,9,2) drawArrow(img,origin,y_axis,yellow,9,2) drawArrow(img,origin,z_axis,blue,9,2) cv2.circle(img,origin,2,black,-1,8)
ce1109644627bf97e4383aefbe2c2da943e15188
[ "Python" ]
2
Python
Bingrong89/DOF6_Python
275af02001dfb94a5985890ec1bbe282ab970667
27cf831f11bbcc5300f0cc2975bbde6c1ed96cee
refs/heads/master
<repo_name>pyrizwan/nodejs-mysql-rest-api-with-jwt-and-swagger<file_sep>/seed.sql -- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Jul 22, 2019 at 08:27 PM -- Server version: 5.7.24-0ubuntu0.18.04.1 -- PHP Version: 7.2.10-0ubuntu0.18.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `seed` -- -- -------------------------------------------------------- -- -- Table structure for table `todo` -- CREATE TABLE `todo` ( `id` int(11) NOT NULL, `created_by` int(11) DEFAULT NULL, `created_on` datetime DEFAULT CURRENT_TIMESTAMP, `task` varchar(255) DEFAULT NULL, `status` varchar(25) DEFAULT 'Pending' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `todo` -- INSERT INTO `todo` (`id`, `created_by`, `created_on`, `task`, `status`) VALUES (1, 1, '2019-07-22 19:01:44', 'string', 'Pending'), (2, 1, '2019-07-22 19:03:13', 'string', 'Pending'), (3, 1, '2019-07-22 19:03:58', 'string', 'Done'), (4, 1, '2019-07-22 19:04:30', 'string', 'Pending'), (6, 1, '2019-07-22 19:05:14', 'string', 'Pending'), (7, 1, '2019-07-22 19:05:36', 'string', 'Pending'), (8, 1, '2019-07-22 19:07:25', 'string', 'Pending'), (9, 1, '2019-07-22 19:07:43', 'string', 'Pending'), (10, 1, '2019-07-22 19:08:12', 'string', 'Pending'), (11, 1, '2019-07-22 19:08:40', 'string', 'Pending'), (12, 1, '2019-07-22 19:09:59', 'string', 'Pending'), (13, 1, '2019-07-22 19:11:18', 'string', 'Pending'), (14, 1, '2019-07-22 19:11:25', 'string', 'Pending'), (15, 1, '2019-07-22 19:12:35', 'string', 'Pending'), (16, 1, '2019-07-22 19:15:59', 'lakslaks', 'Pending'), (17, 1, '2019-07-22 19:21:54', 'string', 'Pending'), (18, 1, '2019-07-22 19:33:16', 'string', 'Pending'), (19, 1, '2019-07-22 19:47:04', 'rizwan', 'Pending'); -- -- Indexes for dumped tables -- -- -- Indexes for table `todo` -- ALTER TABLE `todo` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `todo` -- ALTER TABLE `todo` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=20; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/server.js const express = require('express') const app = express(); const swagger = require('./lib/swagger'); const config = require('./lib/config')(); var bodyParser = require('body-parser'); app.get('/', (req, res) => { res.send('todo app with jwt swagger UI doc => <a href="/docs">/docs</a>'); }); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); const todo = require('./routes/todo'); app.use('/todo', todo); // init swagger if (config.environment === 'local' || config.environment === 'dev') { swagger(app); } console.log(config.environment) app.listen(8000, () => { console.log('Example app listening on port 8000!') });<file_sep>/README.md # nodejs-mysql-rest-api-with-jwt-and-swagger nodejs mysql rest api with jwt and swagger seed project <file_sep>/routes/todo/index.js const express = require("express"); const router = express.Router(); var Todo = require('../../models/todo'); /** * @swagger * /todo: * post: * summary: Add new records in todo list * description: "This API is for Adding new records in todo list" * tags: [Todo] * produces: * - application/json * parameters: * - name: body * description: This contains Detail of Brands as JSON Object. * in: body * required: true * schema: * type: object * required: * - task * properties: * task: * type: string * responses: * 200: * description: This contain to the success message * schema: * type: object * properties: * message: * type: string * 426: * description: "Indicate that version in header is not supported" * 400: * description: "Indicate body parameters are not valid." * 401: * description: "User don't have permissions to execute this API or token is not valid" * 498: * description: "Indicate Auth token is invalid or Expired" */ router.post("/", (req, res, next) => { let data=req.body; let response={}; data.created_by=1; response.status=res.statusCod; Todo.addNew(data, (err, post) => { if (err) { res.send('error:' + err); } else response.message="success"; response.status=true; response.data=""; res.send(response); }); }); /** * @swagger * /todo: * get: * summary: List all todos * description: List all todo as an JSON array * tags: [Todo] * produces: * - application/json * responses: * 200: * description: "successful operation" */ router.get('/', (req, res) => { let response={} Todo.getAll(function(err, result) { if (err) {throw err;} else { response.message="success"; response.status=true; response.data=result; res.send(response); } }); }); /** * @swagger * /todo/{id}: * get: * summary: get todos by id * description: This API is used to get Tax detail. * tags: [Todo] * produces: * - application/json * parameters: * - name: id * description: todo id of list to be retrieved. * in: path * required: true * type: string * responses: * 200: * description: Response contains Category details. * schema: * $ref: '#/definitions/Category' * 426: * description: "Indicate that version in header is not supported" * 401: * description: "User don't have permissions to execute this API or token is not valid" * 498: * description: "Indicate Auth token is invalid or Expired" */ router.get('/:id', (req, res) => { let response={} Todo.getByID(req.params.id, (err, result) => { if (err) {throw err;} else { response.message="success"; response.status=true; response.data=result; res.send(response); } }); }); /** * @swagger * /todo/{id}: * put: * summary: update todo by id * description: This API is for updating. * tags: [Todo] * produces: * - application/json * parameters: * - name: body * description: Application Version. * in: body * required: true * schema: * type: object * required: * - status * properties: * status: * type: string * - name: id * description: id of todo to be updated. * in: path * required: true * type: string * responses: * 200: * description: Response contain success message. * schema: * type: object * properties: * message: * type: string * 426: * description: "Indicate that version in header is not supported" * 404: * description: "Indicate driver_id is not valid." * 401: * description: "User don't have permissions to execute this API or token is not valid" * 498: * description: "Indicate Auth token is invalid or Expired" */ router.put('/:id', (req, res) => { let response={} Todo.update(req.body,req.params.id, (err, result) => { if (err) {throw err;} else { response.message="updated successfully"; response.status=true; response.data=""; res.send(response); } }); }); /** * @swagger * /todo/{id}: * delete: * summary: List all todo * description: This API is for deleting Tax in database. * tags: [Todo] * produces: * - application/json * parameters: * - name: id * description: id of todo to be deleted. * in: path * required: true * type: string * responses: * 200: * description: Response contain success message. * schema: * type: object * properties: * message: * type: string * 426: * description: "Indicate that version in header is not supported" * 404: * description: "Indicate driver_id is not valid." * 401: * description: "User don't have permissions to execute this API or token is not valid" * 498: * description: "Indicate Auth token is invalid or Expired" */ router.delete('/:id', (req, res) => { let response={} Todo.delete(req.params.id, (err, result) => { if (err) {throw err;} else { response.message="deleted successfully"; response.status=true; response.data=""; res.send(response); } }); }); module.exports = router;
36058f997d194531b872638012233539fb79b156
[ "JavaScript", "SQL", "Markdown" ]
4
SQL
pyrizwan/nodejs-mysql-rest-api-with-jwt-and-swagger
f0330179c74af37aa59c0d67ca84a8018f9efa4a
d5086d4456c3dee7405cf7b09426bd14c547a257
refs/heads/master
<file_sep>import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.xbill.DNS.*; public class Main { private final static int BUFFER_SIZE = 8 * 1024; static int port; static Selector selector; private static ServerSocketChannel serverSocketChannel = null; static DatagramChannel dnsChannel; static Map<SocketChannel, ClientChannelHandler> clients = new HashMap<>(); static Map<SocketChannel, ClientChannelHandler> remotes = new HashMap<>(); static HashMap<Integer, ClientChannelHandler> dns = new HashMap<>(); public static void main(String args[]) { if (args.length < 1) { System.err.println("No args were set. Port is 1080"); port = 1080; } else { try { port = Integer.valueOf(args[0]); if (port < 0 || port > 65535) { throw new NumberFormatException(); } } catch (NumberFormatException nfe) { System.err.println("Port value is not correct. Using default (1080)"); port = 1080; } } try { //selector & serverSocketChannel settings: selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.bind(new InetSocketAddress(port)); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); //dns settings: String dnsServers[] = ResolverConfig.getCurrentConfig().servers(); dnsChannel = DatagramChannel.open(); dnsChannel.configureBlocking(false); if (dnsServers.length > 2) { dnsChannel.connect(new InetSocketAddress(dnsServers[2], 53)); } else { dnsChannel.connect(new InetSocketAddress("8.8.8.8", 53)); } dnsChannel.register(selector, SelectionKey.OP_READ); startServer(); } catch (IOException e) { try { serverSocketChannel.close(); dnsChannel.close(); selector.close(); } catch (IOException ex) { ex.printStackTrace(); } e.printStackTrace(); System.exit(-1); } } private static void startServer() throws IOException { System.out.println("Server started"); try { while (true) { selector.select(); for (SelectionKey key : selector.selectedKeys()) { if (key.isValid()) { if (key.isAcceptable() && serverSocketChannel == key.channel()) { SocketChannel socketChannel = serverSocketChannel.accept(); if (socketChannel != null) { ClientChannelHandler handler = new ClientChannelHandler(socketChannel); clients.put(socketChannel, handler); socketChannel.register(selector, SelectionKey.OP_READ); } } else if (key.isConnectable()) ((SocketChannel) key.channel()).finishConnect(); else if (key.isReadable()) { List<ClientChannelHandler> toDestroyList = new LinkedList<>(); if (key.channel() instanceof SocketChannel) { //not a DatagramChannel SocketChannel socketChannel = (SocketChannel) key.channel(); ClientChannelHandler handler = clients.get(socketChannel); if (handler != null) { handler.localRead(); } else { handler = remotes.get(socketChannel); if (handler != null) { handler.remoteRead(); } } if (handler != null) if (handler.isDestroy()) { toDestroyList.add(handler); } } else if (key.channel().equals(dnsChannel)) { //not a SocketChannel ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); int length = dnsChannel.read(buffer); if (length > 0) { Message message = new Message(buffer.array()); Record[] records = message.getSectionArray(1); for (Record record : records) { if (record instanceof ARecord) { ARecord aRecord = (ARecord) record; int id = message.getHeader().getID(); ClientChannelHandler handler = dns.get(id); if (handler != null && aRecord.getAddress() != null) { handler.connect(aRecord.getAddress()); if (handler.isDestroy()) { toDestroyList.add(handler); } } dns.remove(id); break; } } buffer.clear(); } } for (ClientChannelHandler handler : toDestroyList) { handler.destroy(); } } } } } } catch (Exception e) { e.printStackTrace(); } finally { for (SocketChannel channel : remotes.keySet()) { channel.close(); } for (SocketChannel channel : clients.keySet()) { channel.close(); } serverSocketChannel.close(); dnsChannel.close(); selector.close(); } } } <file_sep>path.variable.kotlin_bundled=C\:\\Program Files\\JetBrains\\IntelliJ IDEA 2018.1.1\\plugins\\Kotlin\\kotlinc path.variable.maven_repository=C\:\\Users\\Anton\\.m2\\repository jdk.home.9.0=C\:/Program Files/Java/jdk-9.0.4 javac2.instrumentation.includeJavaRuntime=false<file_sep>import java.io.IOException; import java.net.ConnectException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import org.xbill.DNS.*; class ClientChannelHandler { private final static int BUFFER_SIZE = 8 * 1024; private final static int SOCKS5 = 0x05; private final static int AUTH_NUM = 0x01; //greeting message private final static int NO_AUTH = 0x00; //greeting message private final static int TCP_IP_STREAM_CONNECTION = 0x01; private final static int RESERVED = 0x00; private final static int IPV4 = 0x01; private final static int DNS = 0x03; private final static int SIZE_GREETINGS = 2; private final static int SIZE_CONNECTION = 10; private final static int SIZE_IP = 4; private final static int REQ_GRANTED = 0x00; private final static int ERROR = 0x01; private SocketChannel localSocketChannel; private SocketChannel remoteSocketChannel; private boolean destroy = false; private static final int STAGE_DEFAULT = 0; private static final int STAGE_REGISTERED = 1; private static final int STAGE_CONNECTED = 2; private int stage; private InetAddress address; private int remotePort; ClientChannelHandler(SocketChannel socketChannel) throws IOException { this.localSocketChannel = socketChannel; socketChannel.configureBlocking(false); stage = STAGE_DEFAULT; } void remoteRead() throws IOException { ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); try { if (remoteSocketChannel.isConnected()) { int numBytes = remoteSocketChannel.read(byteBuffer); if (numBytes > 0) { localSocketChannel.write(ByteBuffer.wrap(byteBuffer.array(), 0, numBytes)); } else if (numBytes == -1) { this.destroy = true; } } } catch (IOException e) { if (localSocketChannel.isConnected()) localSocketChannel.close(); if (remoteSocketChannel.isConnected()) remoteSocketChannel.close(); } finally { byteBuffer.clear(); } } void localRead() { ByteBuffer byteBuffer = ByteBuffer.allocate(BUFFER_SIZE); try { int bytes = localSocketChannel.read(byteBuffer); byteBuffer.flip(); if (stage == STAGE_DEFAULT) { if (bytes > 0) { int version = byteBuffer.get(); if (version != SOCKS5) { System.out.println("Incorrect version: " + version); throw new IOException(); } int authNum = byteBuffer.get(); int authMethod = byteBuffer.get(); if (authNum != AUTH_NUM || authMethod != NO_AUTH) { throw new IOException(); } ByteBuffer buf = ByteBuffer.allocate(SIZE_GREETINGS); buf.put((byte) SOCKS5); buf.put((byte) NO_AUTH); localSocketChannel.write(ByteBuffer.wrap(buf.array())); buf.clear(); stage = STAGE_REGISTERED; } else if (bytes == -1) { throw new IOException(); } } else if (stage == STAGE_REGISTERED) { if (bytes > 0) { int version = byteBuffer.get(); if (version != SOCKS5) { System.out.println("Incorrect version: " + version); throw new IOException(); } int commandCode = byteBuffer.get(); int reserved = byteBuffer.get(); if (commandCode != TCP_IP_STREAM_CONNECTION || reserved != RESERVED) { throw new IOException(); } int addressType = byteBuffer.get(); if (addressType == IPV4) { byte[] ip = new byte[SIZE_IP]; byteBuffer.get(ip); address = InetAddress.getByAddress(ip); } else if (addressType == DNS) { int len = byteBuffer.get(); byte[] byteName = new byte[len]; byteBuffer.get(byteName); String nameStr = new String(byteName); Name name = Name.fromString(nameStr, Name.root); Record record = Record.newRecord(name, Type.A, DClass.IN); Message message = Message.newQuery(record); Main.dnsChannel.write(ByteBuffer.wrap(message.toWire())); Main.dns.put(message.getHeader().getID(), this); } else { throw new IOException(); } remotePort = byteBuffer.getShort(); if (addressType == IPV4) { connect(); } } else if (bytes == -1) { throw new IOException(); } } else if (stage == STAGE_CONNECTED) { if (localSocketChannel.isConnected()) { if (bytes > 0) { remoteSocketChannel.write(ByteBuffer.wrap(byteBuffer.array(), 0, bytes)); } else if (bytes == -1) { throw new IOException(); } } } } catch (IOException e) { this.destroy = true; this.destroy(); } finally { byteBuffer.clear(); } } void connect(InetAddress address) throws IOException { this.address = address; this.connect(); } private void connect() throws IOException { try { if (localSocketChannel.isConnected()) { remoteSocketChannel = SocketChannel.open(new InetSocketAddress(this.address, remotePort)); ByteBuffer buffer = ByteBuffer.allocate(SIZE_CONNECTION); buffer.put((byte) SOCKS5); buffer.put(remoteSocketChannel.isConnected() ? (byte) REQ_GRANTED : (byte) ERROR); buffer.put((byte) RESERVED); buffer.put((byte) IPV4); buffer.put(InetAddress.getLocalHost().getAddress()); buffer.putShort((short) Main.port); localSocketChannel.write(ByteBuffer.wrap(buffer.array())); buffer.clear(); if (!remoteSocketChannel.isConnected()) { this.destroy = true; return; } remoteSocketChannel.configureBlocking(false); remoteSocketChannel.register(Main.selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT); Main.remotes.put(remoteSocketChannel, this); stage = STAGE_CONNECTED; } } catch (ConnectException e) { System.out.println(e.getMessage()); if (localSocketChannel.isConnected()) localSocketChannel.close(); if (remoteSocketChannel != null && remoteSocketChannel.isConnected()) remoteSocketChannel.close(); } finally { if (!this.localSocketChannel.isConnected()) this.destroy = true; } } boolean isDestroy() { return destroy; } void destroy() { if (this.localSocketChannel != null) { try { Main.clients.remove(this.localSocketChannel); this.localSocketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (this.remoteSocketChannel != null) { try { Main.remotes.remove(this.remoteSocketChannel); this.remoteSocketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
4a47c535bb895c9ef3cf8fa21bde399dcbb8946d
[ "Java", "INI" ]
3
Java
antrzm/SOCKS5-proxy
7d72dace8fc2c98cbb6dd4040ccbeb18498058ad
1d6b258668f8097fd9ee04e7178404da1c1f1f71
refs/heads/master
<file_sep>export const host= 'mongodb://localhost:27017/coffe' <file_sep>import mongoose from 'mongoose' import { host } from '../../config/db' const Schema = mongoose.Schema let db = mongoose.createConnection(host) let shopSchema= new Schema( { categories: [[String]], display_phone: String, distance: Number, id: String, image_url: String, is_claimed: Boolean, is_closed: Boolean, location: { address: [String], city: String, coordinate: { latitude: Number, longitude: Number }, country_code: String, display_address: [String], geo_accuracy: Number, neighborhoods: [String], postal_code: String, state_code: String }, mobile_url: String, name: String, phone: String, rating: Number, rating_img_url: String, rating_img_url_large: String, rating_img_url_small: String, review_count: Number, snippet_image_url: String, snippet_text: String, url: String }, {collection: 'shop'} ) export default db.model('shop', shopSchema)<file_sep>import { GraphQLSchema } from 'graphql' import Query from './coffe.Query' import Mutation from './coffe.Mutation' export default new GraphQLSchema({ query: Query //mutation: Mutation }) <file_sep>import express from 'express' import graphqlHTTP from 'express-graphql' import CoffeSchema from '../graphql/coffe/coffe.Schema' let router = express.Router() router.get('/', graphqlHTTP({ schema: CoffeSchema, graphiql: true })) router.post('/', graphqlHTTP({ schema: CoffeSchema, graphiql: false })) export default router<file_sep>import { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLFloat, GraphQLList, GraphQLNonNull, GraphQLBoolean } from 'graphql' export default new GraphQLObjectType({ name: 'Coffe.Shop', fields: () => ({ categories: new GraphQLList(new GraphQLList(GraphQLString)), display_phone: GraphQLString, distance: GraphQLFloat, id: GraphQLString, image_url: GraphQLString, is_claimed: GraphQLBoolean, is_closed: GraphQLBoolean, location: { address: new GraphQLList(GraphQLString), city: GraphQLString, coordinate: { latitude: GraphQLFloat, longitude: GraphQLFloat }, country_code: GraphQLString, display_address: new GraphQLList(GraphQLString), geo_accuracy: GraphQLFloat, neighborhoods: new GraphQLList(GraphQLString), postal_code: GraphQLString, state_code: GraphQLString }, mobile_url: GraphQLString, name: GraphQLString, phone: GraphQLString, rating: GraphQLInt, rating_img_url: GraphQLString, rating_img_url_large: StrGraphQLStringing, rating_img_url_small: GraphQLString, review_count: GraphQLInt, snippet_image_url: GraphQLString, snippet_text: GraphQLString, url: GraphQLString }) })<file_sep>import { GraphQLObjectType } from 'graphql' export default new GraphQLObjectType({ name: 'Coffe Mutation' })
320b1e1ba413a27691261f1f58bbe220ee6c38b6
[ "JavaScript" ]
6
JavaScript
huynhhoang4dev/graphql
4192e123240baae2f801e38a6ee57b98c8686808
feae16d4313cb88a363e140749a4ab87017d15fc
refs/heads/master
<repo_name>peterjc123/randomtemp<file_sep>/randomtemp/randomtemp.h // randomtemp.h : Include file for standard system include files, // or project specific include files. #pragma once #define _CRT_SECURE_NO_WARNINGS <file_sep>/README.md # RandomTemp A utility to override the temp directory for an executable ## Why do we need this? Sometimes, the executables use `TMP` and `TEMP` for finding the temporary directory. However, when you run them in parallel, it is possible that they will write to a file at the same time. We want to avoid this situation, so this utility is written. ## How to use this? Simple usage: ```cmd set RANDOMTEMP_EXECUTABLE=set ./randomtemp.exe :: you may notice that the variables are overriden ``` More complicated case: ```cmd set RANDOMTEMP_EXECUTABLE=nvcc ./randomtemp.exe -v -ccbin ^ "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\bin\HostX64\x64\cl.exe" ^ "test.cpp" :: you may notice that the generated temp directories are used ``` ## Environment variables - RANDOMTEMP_EXECUTABLE: target executable to be patched (Required) - RANDOMTEMP_BASEDIR: directory to store temporary files (Optional, default: current working directory) - RANDOMTEMP_MAXTRIAL: max times for retry the command (Optional, default: 3) ## How to build this? Dependencies: - Visual Studio 2017 / 2019 - CMake 3.14 You may just open it using VS GUI. Alternatively, you may run the following commands to compile it. ```powershell mkdir build cd build cmake -G "Visual Studio 15 2017" -Ax64 .. cmake --build . --config Release ``` ## Limitations 1. It is currently only tested on Windows, but should be fairly use to adapt to Unix systems. 2. All the arguments passed to the executable get quoted. <file_sep>/randomtemp/randomtemp.cpp // randomtemp.cpp : Defines the entry point for the application. // #include "randomtemp.h" #include <direct.h> #include <fcntl.h> #include <io.h> #include <process.h> #include <sys/stat.h> #include <cstdlib> #include <iostream> #include <memory> #include <random> using namespace std; _declspec(dllimport) extern char** _environ; char* mkdtemp(char* tmpl) { int len; char* name; int r = -1; int save_errno = errno; len = static_cast<int>(strlen(tmpl)); if (len < 6 || strncmp(&tmpl[len - 6], "XXXXXX", 6)) { return nullptr; } name = &tmpl[len - 6]; std::random_device rd; do { for (unsigned i = 0; i < 6; ++i) { name[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[rd() % 36]; } r = _mkdir(tmpl); } while (errno == EEXIST); if (r >= 0) { errno = save_errno; return tmpl; } else { return nullptr; } } void removeAll(const char* dir, bool removeSelf = true) { char* cwd; if ((cwd = _getcwd(nullptr, 0)) == nullptr) { perror("_getcwd error"); exit(1); } if (_chdir(dir) != 0) { perror("_chdir error"); exit(1); } _finddata_t data; intptr_t handle = _findfirst("*", &data); if (handle == -1) { return; } do { if (strcmp(data.name, ".") == 0 || strcmp(data.name, "..") == 0) { continue; } if (data.attrib & _A_SUBDIR) { removeAll(data.name); } else { if (remove(data.name) != 0) { perror("_rmdir error"); } } } while (_findnext(handle, &data) != -1); _findclose(handle); if (_chdir(cwd) != 0) { perror("_chdir error"); exit(1); } if (removeSelf) { if (_rmdir(dir) != 0) { perror("_rmdir error"); } } } int main(int argc, const char** argv) { char* cwd; char* tempdir; char* tmpl; char* executable = getenv("RANDOMTEMP_EXECUTABLE"); if (executable == nullptr) { cerr << "you must specify RANDOMTEMP_EXECUTABLE through the environmental variable" << endl; exit(1); } cwd = getenv("RANDOMTEMP_BASEDIR"); if (cwd == nullptr) { if ((cwd = _getcwd(nullptr, 0)) == nullptr) { perror("_getcwd error"); exit(1); } } else { struct _stat st; if (_stat(cwd, &st) != 0) { perror("_stat error"); exit(1); } if ((st.st_mode & _S_IFDIR) != _S_IFDIR) { cerr << "RANDOMTEMP_BASEDIR: " << cwd << " is not a directory." << endl; exit(1); } } tmpl = strcat(cwd, "\\XXXXXX"); tempdir = mkdtemp(tmpl); if (tempdir == nullptr) { perror("mkdtemp error"); exit(1); } std::vector<const char*> env_list; char** env = _environ; while (env != nullptr) { const char* environ_item = const_cast<const char*>(*env); if (environ_item == nullptr) { break; } if (strncmp(environ_item, "TMP=", 4) != 0 && strncmp(environ_item, "TEMP=", 5) != 0) { env_list.push_back(environ_item); } env++; } char tmp_item[_MAX_PATH] = "TMP="; char temp_item[_MAX_PATH] = "TEMP="; env_list.push_back(strcat(tmp_item, tempdir)); env_list.push_back(strcat(temp_item, tempdir)); env_list.push_back(nullptr); char* comspec = getenv("COMSPEC"); if (comspec == nullptr) { comspec = "C:\\Windows\\System32\\cmd.exe"; } vector<const char*> args = { "/q", "/c", executable }; char* escaped_arg; for (int i = 1; i < argc; i++) { escaped_arg = new char[_MAX_PATH + 2](); strcat(escaped_arg, "\""); strcat(escaped_arg, argv[i]); strcat(escaped_arg, "\""); args.push_back(escaped_arg); } args.push_back(nullptr); char* max_trial = getenv("RANDOMTEMP_MAXTRIAL"); int max_times = 3; if (max_trial) { max_times = atoi(max_trial); } intptr_t r; int retry_times = 0; do { if (retry_times > 0) { removeAll(tempdir, false); cout << "Retry attempt " << retry_times << ":" << endl; } r = _spawnve(_P_WAIT, comspec, args.data(), env_list.data()); retry_times++; } while (r != 0 && retry_times <= max_times); removeAll(tempdir); return static_cast<int>(r); }
ae4aeac3280212ab84b25a8d614ac62dd8b4496a
[ "Markdown", "C", "C++" ]
3
C
peterjc123/randomtemp
85985beaf701f1348d84463437ee1b9ebc49bf67
1089b14f83de60300b62cfda5d37b36fc1b915d2
refs/heads/master
<file_sep>import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; //import java.util.List; public class ReadMeterEvi { public static void main(String[] args) throws FileNotFoundException, XMLStreamException { List<Evidence> evidenceList = new ArrayList<>(); Evidence evidence = null; int i = 0; File file = new File("C:\\Users\\Muratn\\Desktop\\Books\\1.xml"); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = factory.createXMLStreamReader(new FileReader(file)); while (streamReader.hasNext()){ streamReader.next(); if (streamReader.getEventType() == XMLStreamReader.START_ELEMENT){ if (streamReader.getLocalName().equalsIgnoreCase("mval2")){ evidence = new Evidence(); if(streamReader.getAttributeCount() > 0) { String id = streamReader.getAttributeValue(null,"id"); evidence.setcTime(id); } } if (streamReader.getLocalName().equalsIgnoreCase("serialno")){ evidence.setSerialNo(streamReader.getElementText()); } if (streamReader.getLocalName().equalsIgnoreCase("value")){ evidence.setmValue(streamReader.getElementText()); } if (streamReader.getLocalName().equalsIgnoreCase("time")){ evidence.setcTime(streamReader.getElementText()); } if (streamReader.getLocalName().equalsIgnoreCase("devtype")){ evidence.setDevType(streamReader.getElementText()); } } if (streamReader.getEventType() == XMLStreamReader.END_ELEMENT){ if (streamReader.getLocalName().equalsIgnoreCase("mval2")){ i = i + 1; evidenceList.add(evidence); System.out.println("№ сч.:" + evidence.getSerialNo() + ", Показан. " + evidence.getmValue() + ", Кол-во: "+i); } } } DbConnect dbConnect = new DbConnect(); for (Evidence item:evidenceList){ Evidence evidence1 = new Evidence(item.getSerialNo(), item.getmValue(), item.getDevType(), item.getcTime()); dbConnect.addEvidence(evidence1); System.out.println(item.getSerialNo()); } System.out.println("Процесс окончен"); } } <file_sep>public class Evidence { private String serialNo, cTime; private String mValue; private String devType; public Evidence(String serialNo, String cTime, String mValue, String devType) { this.serialNo = serialNo; this.cTime = cTime; this.mValue = mValue; this.devType = devType; } }
9f2aa973998c6a8c9b1fcf7687059f4d5c8032a6
[ "Java" ]
2
Java
Muratik88/Java_test
776c055955020c3c737583adcd31a595f87c9c65
7310a2cd4106bdece2ad3bee3f24dcbf69fa5f1c
refs/heads/master
<repo_name>toaster99/tpo<file_sep>/src/utilities/Ranges.js const getFocusElement = () => { let node = document.getSelection().focusNode; if (!node) { return null; } while (node.nodeType !== Node.ELEMENT_NODE) { node = node.parentNode; } return (node.tagName === 'BODY') ? null : node; }; const substituteElement = ($old, tagName) => { const $new = document.createElement(tagName); $new.setAttribute('message', $old.textContent); // $new.textContent = $old.textContent; $old.parentNode.replaceChild($new, $old); return $new; }; const selectElement = ($element, collapseToStart) => { const offset = collapseToStart ? 0 : 1; // Collapse to end by default document.getSelection().collapse($element, offset); }; export { getFocusElement, substituteElement, selectElement };
86f1620b4f4a8fa8ea751020cf7d02ceab4c7ed6
[ "JavaScript" ]
1
JavaScript
toaster99/tpo
4ed7fd38ce6eb642924a941413a6a995dc336e59
c9bbc595f7c8709feefabe9eb18327f3f38a9f53
refs/heads/master
<repo_name>sampletext-projects/Dmitriev_2_2<file_sep>/Dmitriev_2_2/main.cpp #include <iostream> #include <math.h> #include <iomanip> #include <conio.h> using namespace std; class Triangle { double side1; double side2; double side3; double angle1; double angle2; double angle3; public: Triangle() //init { side1 = 0.0; side2 = 0.0; side3 = 0.0; angle1 = 0.0; angle2 = 0.0; angle3 = 0.0; } Triangle(double side1_, double side2_, double side3_, double angle1_, double angle2_, double angle3_) //read { side1 = side1_; side2 = side2_; side3 = side3_; angle1 = angle1_; angle2 = angle2_; angle3 = angle3_; } Triangle(Triangle& obj) { side1 = obj.side1; side2 = obj.side2; side3 = obj.side3; angle1 = obj.angle1; angle2 = obj.angle2; angle3 = obj.angle3; } double get_side1() { return side1; } double get_side2() { return side2; } double get_side3() { return side3; } double get_angle1() { return angle1; } double get_angle2() { return angle2; } double get_angle3() { return angle3; } void set_side1(double side1_) { side1 = side1_; } void set_side2(double side2_) { side2 = side2_; } void set_side3(double side3_) { side3 = side3_; } void set_angle1(double angle1_) { angle1 = angle1_; } void set_angle2(double angle2_) { angle2 = angle2_; } void set_angle3(double angle3_) { angle3 = angle3_; } double get_perimeter() { return side1 + side2 + side3; } double get_square() { double a = side1; double b = side2; double c = side3; double p = get_perimeter() / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); } double get_height_to_side1() { return (2 * get_square()) / side1; } double get_height_to_side2() { return (2 * get_square()) / side2; } double get_height_to_side3() { return (2 * get_square()) / side3; } void check_triangle() { if (side1 == side2 && side2 == side3 && side1 == side3) { cout << "Треугольник равносторонний " << endl; } else if (side1 == side2 || side2 == side3 || side1 == side3) { cout << "Треугольник равнобедренный " << endl; } if ((side1 == side2 || side2 == side3 || side1 == side3) && (angle1 == 90 || angle2 == 90 || angle3 == 90)) { cout << "Треугольник равнобедренный и прямоугольный " << endl; } if (angle1 == 90 || angle2 == 90 || angle3 == 90) { cout << "Треугольник прямоугольный " << endl; } } friend ostream& operator<<(ostream& os, Triangle& obj); friend istream& operator>>(istream& is, Triangle& obj); }; ostream& operator<<(ostream& os, Triangle& obj) { os << "1-я сторона:" << obj.side1 << endl; os << "2-я сторона:" << obj.side2 << endl; os << "3-я сторона:" << obj.side3 << endl; os << "1-й угол:" << obj.angle1 << endl; os << "2-й угол:" << obj.angle2 << endl; os << "3-й угол:" << obj.angle3 << endl; return os; } istream& operator>>(istream& is, Triangle& obj) { cout << "Введите 1-ю сторону:"; is >> obj.side1; cout << "Введите 2-ю сторону:"; is >> obj.side2; cout << "Введите 3-ю сторону:"; is >> obj.side3; cout << "Введите 1-й угол:"; is >> obj.angle1; cout << "Введите 2-й угол:"; is >> obj.angle2; cout << "Введите 3-й угол:"; is >> obj.angle3; return is; } int main() { setlocale(LC_ALL, "Russian"); Triangle triangle1; cout << triangle1; Triangle triangle2; cin >> triangle2; cout << "Получаем первую сторону треугольника: " << triangle2.get_side1() << endl; cout << "На какое число изменить данную сторону треугольника: "; double delta; cin >> delta; triangle2.set_side1(delta); cout << "Теперь вот Ваша сторона:" << triangle2.get_side1() << endl; cout << "Периметр треугольника:" << triangle2.get_perimeter() << endl; cout << "Площадь треугольника:" << triangle2.get_square() << endl; cout << "Высота треугольника,основанием которой является первая сторона треугольника:" << triangle2. get_height_to_side1() << endl; triangle2.check_triangle(); _getch(); }
c96a3ac7b96d89e9251a1bd0db23fa47e2a842e8
[ "C++" ]
1
C++
sampletext-projects/Dmitriev_2_2
6b6e304f03f6f77c3ff8082a4145ef2b7315c50b
af2b97179b7d792d25535ce9e325d63ea9fdfbfb
refs/heads/master
<file_sep># -*- Coding: utf-8 -*- import os import subprocess import datetime from time import sleep def main(): dt_now = datetime.datetime.now() print(dt_now.strftime('%Y/%m/%d %H:%M:%S') + "10秒更新中...") print(os.environ.get('LANG')) #print(os.environ.get('RemoteENV')) if __name__ == '__main__': while True: main() sleep(10)
dc08695a3c82c4aa55be89ddeb06cc58722330fe
[ "Python" ]
1
Python
u1-iot/IoT_skill_pack_starting
2f06045f744a1ee0f1072a9ae96c21aac5e407ce
028e585efd882d617c20116b65ae34ba72e54357
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import models.ModelMenuAdmin; import views.ViewMenuAdmin; import com.jcraft.jsch.JSchException; /** * * @author Octaviano */ public final class ControllerMenuAdmin { private final ModelMenuAdmin ModelMenuAdmin; private final ViewMenuAdmin viewMenuAdmin; /** * Esta variable almacena los controladores de cada vista de catalogos para * poder utilizarlos dentro del mismo JFrame. */ private Object controllers[]; private ControllerClientes controllerClientes; private ControllerEmpleadosCompras controllerEmpleadosCompras; private ControllerEmpleadosVentas controllerEmpleadosVentas; private ControllerProductos controllerProductos; private ControllerProveedores controllerProveedores; private ControllerSucursales controllerSucursales; private ControllerAgregarSucursal controllerAgregarSucursal; private ControllerDetalleCompra controllerDetalleCompra; private ControllerDetalleVentas controllerDetalleVentas; private ControllerPromociones controllerPromociones; private ControllerDescuentos controllerDescuentos; /** * Controlador principal donde se un el modelo y controlador del MenuAdmin * Recibe cada controlador de las vistas de los catalogos dentro de este * controlador se tiene el accesso a la programacion en el controlador de * cada JpanelCatalogo * * @param modelMenuAdmin * @param ViewMenuAdmin * @param controllers */ public ControllerMenuAdmin(ModelMenuAdmin ModelMenuAdmin, ViewMenuAdmin viewMenuAdmin, Object[] controllers) { this.ModelMenuAdmin = ModelMenuAdmin; this.viewMenuAdmin = viewMenuAdmin; this.controllers = controllers; ModelMenuAdmin.Conectar(); setControllers(); setActionListener(); initComponets(); } /** * Separa cada uno de los controlladores almacendados en controllers, de * esta forma se puede acceder a todas las variables y métodos publicos de * cada uno. */ public void setControllers() { controllerClientes = (ControllerClientes) controllers[0]; controllerEmpleadosCompras = (ControllerEmpleadosCompras) controllers[1]; controllerEmpleadosVentas = (ControllerEmpleadosVentas) controllers[2]; controllerProductos = (ControllerProductos) controllers[3]; controllerProveedores = (ControllerProveedores) controllers[4]; controllerSucursales = (ControllerSucursales) controllers[5]; controllerAgregarSucursal = (ControllerAgregarSucursal) controllers[6]; controllerDetalleCompra = (ControllerDetalleCompra) controllers[7]; controllerDetalleVentas = (ControllerDetalleVentas) controllers[8]; controllerPromociones = (ControllerPromociones) controllers[9]; controllerDescuentos = (ControllerDescuentos) controllers[10]; } /** * mustra la ventana principal del menuAdmin */ private void initComponets() { viewMenuAdmin.setTitle("Menu Administrador"); viewMenuAdmin.setLocationRelativeTo(null); viewMenuAdmin.setVisible(true); } /** * Asigna el actionListener a cada uno de los JMenuItems de la vista * ViewMenuAdmin. */ private void setActionListener() { viewMenuAdmin.jmi_clientes.addActionListener(actionListener); viewMenuAdmin.jmi_empleados_compras.addActionListener(actionListener); viewMenuAdmin.jmi_empleados_ventas.addActionListener(actionListener); viewMenuAdmin.jmi_productos.addActionListener(actionListener); viewMenuAdmin.jmi_proveedores.addActionListener(actionListener); viewMenuAdmin.jmi_sucursales.addActionListener(actionListener); viewMenuAdmin.jmi_agregar_Sucursal.addActionListener(actionListener); viewMenuAdmin.jmi_detallecompra.addActionListener(actionListener); viewMenuAdmin.jmi_detalleventa.addActionListener(actionListener); viewMenuAdmin.jmi_promociones.addActionListener(actionListener); viewMenuAdmin.jmi_descuentos.addActionListener(actionListener); viewMenuAdmin.jmi_salir.addActionListener(actionListener); viewMenuAdmin.jmi_respaldoBD.addActionListener(actionListener); } /** * Evalua el componente que genero el evento y llama a un método en * particular. */ private final ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewMenuAdmin.jmi_clientes) { jmi_clientes_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_empleados_compras) { jmi_Empleados_compras_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_empleados_ventas) { jmi_Empleados_ventas_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_productos) { jmi_productos_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_proveedores) { jmi_proveedores_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_sucursales) { jmi_sucursales_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_agregar_Sucursal) { jm_AgregarSucursales_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_detallecompra) { jmi_detallecompra_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_detalleventa) { jmi_detalleventa_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_promociones) { jmi_promociones_actionPerformed(); } else if (e.getSource() == viewMenuAdmin.jmi_descuentos) { jmi_descuentos_actionPerformed(); }else if (e.getSource() == viewMenuAdmin.jmi_salir) { ModelMenuAdmin.VentanaLogin(); viewMenuAdmin.setVisible(false); }else if (e.getSource() == viewMenuAdmin.jmi_respaldoBD) { Respaldo(); jmi_respaldoBD_actionPerformed(); } } }; /** * Muestra el JPanel ViewClientes dentro del JFrame ViewMenuAdmin, (incluido * todo el funcionamiendo programado). */ private void jmi_clientes_actionPerformed() { viewMenuAdmin.setContentPane(controllerClientes.viewClientes); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_Empleados_compras_actionPerformed() { viewMenuAdmin.setContentPane(controllerEmpleadosCompras.viewEmpleadosCompras); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_Empleados_ventas_actionPerformed() { viewMenuAdmin.setContentPane(controllerEmpleadosVentas.viewsEmpleadosVentas); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_productos_actionPerformed() { viewMenuAdmin.setContentPane(controllerProductos.viewProductos); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_proveedores_actionPerformed() { viewMenuAdmin.setContentPane(controllerProveedores.viewProveedores); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_sucursales_actionPerformed() { viewMenuAdmin.setContentPane(controllerSucursales.viewSucursales); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jm_AgregarSucursales_actionPerformed() { viewMenuAdmin.setContentPane(controllerAgregarSucursal.viewAgregarSucursal); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_detallecompra_actionPerformed() { viewMenuAdmin.setContentPane(controllerDetalleCompra.viewDetalleCompra); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_detalleventa_actionPerformed() { viewMenuAdmin.setContentPane(controllerDetalleVentas.viewDetalleVentas); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_promociones_actionPerformed() { viewMenuAdmin.setContentPane(controllerPromociones.viewPromociones); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_descuentos_actionPerformed() { viewMenuAdmin.setContentPane(controllerDescuentos.viewDescuentos); viewMenuAdmin.revalidate(); viewMenuAdmin.repaint(); } private void jmi_respaldoBD_actionPerformed() { ModelMenuAdmin.respaldosDBLocal(); } private static final String USERNAME = "pi"; private static final String HOST ="proxy18.rt3.io"; private static final int PORT =39648; private static final String PASSWORD = "<PASSWORD>"; private void Respaldo(){ try { ModelMenuAdmin.connect(USERNAME,PASSWORD,HOST,PORT); String result = ModelMenuAdmin.executeCommand("mysqldump -u tic41 -p --password=<PASSWORD> StockCia> respaldoManualCIA/Base_de_Datos/StockCiaManual.sql"); ModelMenuAdmin.disconnect(); System.out.println(result); JOptionPane.showMessageDialog(null, "La base de datos ha sido respaldada en el servidor"); } catch (JSchException | IllegalAccessException | IOException ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewLogin extends javax.swing.JFrame { /** * Creates new form LOGIN */ public ViewLogin() { initComponents(); this.setLocationRelativeTo(null); this.setOpacity(0.95f); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jl_passwd = new javax.swing.JLabel(); jcb_tipo_admin = new javax.swing.JComboBox<>(); jl_tipo = new javax.swing.JLabel(); jl_usuario = new javax.swing.JLabel(); jpf_passwd = new javax.swing.JPasswordField(); jtf_usuario = new javax.swing.JTextField(); jb_aceptar = new javax.swing.JButton(); jb_cancelar = new javax.swing.JButton(); jl_fondo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Iniciar Sesion"); setMaximumSize(new java.awt.Dimension(604, 503)); setMinimumSize(new java.awt.Dimension(604, 503)); setUndecorated(true); getContentPane().setLayout(null); jl_passwd.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N jl_passwd.setText("Contraseña:"); getContentPane().add(jl_passwd); jl_passwd.setBounds(240, 250, 100, 25); jcb_tipo_admin.setBackground(new java.awt.Color(204, 204, 204)); jcb_tipo_admin.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jcb_tipo_admin.setForeground(new java.awt.Color(0, 153, 204)); jcb_tipo_admin.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Administrador", "Empleado Ventas", "Empleado Compras" })); jcb_tipo_admin.setBorder(null); getContentPane().add(jcb_tipo_admin); jcb_tipo_admin.setBounds(340, 110, 190, 30); jl_tipo.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N jl_tipo.setText("TIPO:"); getContentPane().add(jl_tipo); jl_tipo.setBounds(280, 110, 40, 25); jl_usuario.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N jl_usuario.setText("Usuario:"); getContentPane().add(jl_usuario); jl_usuario.setBounds(270, 180, 60, 25); jpf_passwd.setHorizontalAlignment(javax.swing.JTextField.CENTER); jpf_passwd.setText("<PASSWORD>"); jpf_passwd.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(51, 102, 255), null, null)); getContentPane().add(jpf_passwd); jpf_passwd.setBounds(340, 250, 190, 30); jtf_usuario.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_usuario.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(51, 102, 255), null, null)); getContentPane().add(jtf_usuario); jtf_usuario.setBounds(340, 180, 190, 30); jb_aceptar.setBackground(new java.awt.Color(51, 153, 255)); jb_aceptar.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N jb_aceptar.setForeground(new java.awt.Color(255, 255, 255)); jb_aceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/aceptar.png"))); // NOI18N jb_aceptar.setText("Aceptar"); jb_aceptar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 102, 153))); // NOI18N getContentPane().add(jb_aceptar); jb_aceptar.setBounds(90, 380, 120, 50); jb_cancelar.setBackground(new java.awt.Color(51, 153, 255)); jb_cancelar.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N jb_cancelar.setForeground(new java.awt.Color(255, 255, 255)); jb_cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cerrar.png"))); // NOI18N jb_cancelar.setText("cancelar"); jb_cancelar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 102, 153))); // NOI18N getContentPane().add(jb_cancelar); jb_cancelar.setBounds(290, 380, 130, 50); jl_fondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/login.png"))); // NOI18N getContentPane().add(jl_fondo); jl_fondo.setBounds(0, 1, 600, 500); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewLogin().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JButton jb_aceptar; public javax.swing.JButton jb_cancelar; public javax.swing.JComboBox<String> jcb_tipo_admin; public javax.swing.JLabel jl_fondo; public javax.swing.JLabel jl_passwd; public javax.swing.JLabel jl_tipo; public javax.swing.JLabel jl_usuario; public javax.swing.JPasswordField jpf_passwd; public javax.swing.JTextField jtf_usuario; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewProveedores extends javax.swing.JPanel { /** * Creates new form Clientes */ public ViewProveedores() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jp_barra = new javax.swing.JPanel(); jl_titulo = new javax.swing.JLabel(); jl_imagen = new javax.swing.JLabel(); jl_icon_buscar = new javax.swing.JLabel(); jtf_buscar = new javax.swing.JTextField(); jp_datos = new javax.swing.JPanel(); jl_telefono = new javax.swing.JLabel(); jtf_apt_mat = new javax.swing.JTextField(); jl_ap_pat = new javax.swing.JLabel(); jtf_telefono = new javax.swing.JTextField(); jl_id = new javax.swing.JLabel(); jtf_id = new javax.swing.JTextField(); jl_ap_mat = new javax.swing.JLabel(); jtf_ap_pat = new javax.swing.JTextField(); jl_nombre = new javax.swing.JLabel(); jtf_nombre = new javax.swing.JTextField(); jl_Provincia = new javax.swing.JLabel(); jl_calle = new javax.swing.JLabel(); jtf_colonia = new javax.swing.JTextField(); jtf_municipio = new javax.swing.JTextField(); jl_correo = new javax.swing.JLabel(); jl_numero = new javax.swing.JLabel(); jtf_correo = new javax.swing.JTextField(); jtf_numero = new javax.swing.JTextField(); jtf_provincia = new javax.swing.JTextField(); jl_colonia = new javax.swing.JLabel(); jp_botones = new javax.swing.JPanel(); jb_nuevo = new javax.swing.JButton(); jl_nuevo = new javax.swing.JLabel(); jb_modificar = new javax.swing.JButton(); jl_modificar = new javax.swing.JLabel(); jb_eliminar = new javax.swing.JButton(); jl_eliminar = new javax.swing.JLabel(); jb_guardar = new javax.swing.JButton(); jl_guadar = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jt_vista = new javax.swing.JTable(); setBackground(new java.awt.Color(255, 255, 255)); jp_barra.setBackground(new java.awt.Color(153, 204, 255)); jl_titulo.setFont(new java.awt.Font("Segoe UI", 0, 50)); // NOI18N jl_titulo.setForeground(new java.awt.Color(102, 102, 102)); jl_titulo.setText("Proveedores"); jl_imagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/proveedores.png"))); // NOI18N javax.swing.GroupLayout jp_barraLayout = new javax.swing.GroupLayout(jp_barra); jp_barra.setLayout(jp_barraLayout); jp_barraLayout.setHorizontalGroup( jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_barraLayout.createSequentialGroup() .addGap(44, 44, 44) .addComponent(jl_titulo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jl_imagen) .addGap(61, 61, 61)) ); jp_barraLayout.setVerticalGroup( jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_barraLayout.createSequentialGroup() .addGroup(jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_imagen) .addComponent(jl_titulo)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jl_icon_buscar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jl_icon_buscar.setForeground(new java.awt.Color(0, 153, 204)); jl_icon_buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jl_icon_buscar.setText("Buscar por ID..."); jp_datos.setBackground(new java.awt.Color(255, 255, 255)); jp_datos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 14), new java.awt.Color(0, 153, 255))); // NOI18N jl_telefono.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_telefono.setForeground(new java.awt.Color(51, 51, 51)); jl_telefono.setText("Telefono:"); jl_ap_pat.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_ap_pat.setForeground(new java.awt.Color(51, 51, 51)); jl_ap_pat.setText("Apellido Paterno:"); jl_id.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_id.setForeground(new java.awt.Color(51, 51, 51)); jl_id.setText("ID:"); jl_ap_mat.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_ap_mat.setForeground(new java.awt.Color(51, 51, 51)); jl_ap_mat.setText("Apellido Materno:"); jl_nombre.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nombre.setForeground(new java.awt.Color(51, 51, 51)); jl_nombre.setText("Nombre:"); jl_Provincia.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_Provincia.setForeground(new java.awt.Color(51, 51, 51)); jl_Provincia.setText("Provincia:"); jl_calle.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_calle.setForeground(new java.awt.Color(51, 51, 51)); jl_calle.setText("Calle:"); jl_correo.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_correo.setForeground(new java.awt.Color(51, 51, 51)); jl_correo.setText("Correo:"); jl_numero.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_numero.setForeground(new java.awt.Color(51, 51, 51)); jl_numero.setText("Numero:"); jl_colonia.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_colonia.setForeground(new java.awt.Color(51, 51, 51)); jl_colonia.setText("Colonia:"); javax.swing.GroupLayout jp_datosLayout = new javax.swing.GroupLayout(jp_datos); jp_datos.setLayout(jp_datosLayout); jp_datosLayout.setHorizontalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_nombre) .addComponent(jl_id)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jtf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jl_numero)) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jtf_id, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_ap_mat) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_apt_mat, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_ap_pat) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_ap_pat, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_telefono) .addComponent(jl_calle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_municipio, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(64, 64, 64) .addComponent(jl_colonia) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_colonia, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(51, 51, 51) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_correo) .addComponent(jl_Provincia)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_correo, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_provincia, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_numero, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jp_datosLayout.setVerticalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_id) .addComponent(jtf_id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(9, 9, 9) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nombre) .addComponent(jtf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_ap_pat) .addComponent(jtf_ap_pat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_ap_mat) .addComponent(jtf_apt_mat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(78, 78, 78) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_colonia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_colonia))) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_telefono)) .addGap(16, 16, 16) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_municipio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_calle))) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_numero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_numero)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_provincia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_Provincia)))) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_correo) .addComponent(jtf_correo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(23, Short.MAX_VALUE)) ); jp_botones.setBackground(new java.awt.Color(255, 255, 51)); jb_nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/nuevo.png"))); // NOI18N jl_nuevo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_nuevo.setForeground(new java.awt.Color(51, 51, 51)); jl_nuevo.setText("Nuevo"); jb_modificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Modificar.png"))); // NOI18N jl_modificar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_modificar.setForeground(new java.awt.Color(51, 51, 51)); jl_modificar.setText("Modificar"); jb_eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/eliminar.png"))); // NOI18N jl_eliminar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_eliminar.setForeground(new java.awt.Color(51, 51, 51)); jl_eliminar.setText("Eliminar"); jb_guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Guardar.png"))); // NOI18N jb_guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jb_guardarActionPerformed(evt); } }); jl_guadar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_guadar.setForeground(new java.awt.Color(51, 51, 51)); jl_guadar.setText("Guardar"); javax.swing.GroupLayout jp_botonesLayout = new javax.swing.GroupLayout(jp_botones); jp_botones.setLayout(jp_botonesLayout); jp_botonesLayout.setHorizontalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_botonesLayout.createSequentialGroup() .addContainerGap(79, Short.MAX_VALUE) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jl_nuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(48, 48, 48) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_modificar)) .addGap(28, 28, 28) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_eliminar)) .addGap(34, 34, 34) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_guadar)) .addGap(88, 88, 88)) ); jp_botonesLayout.setVerticalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jp_botonesLayout.createSequentialGroup() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nuevo) .addComponent(jl_modificar) .addComponent(jl_eliminar) .addComponent(jl_guadar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jt_vista.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jt_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null} }, new String [] { "ID", "Nombre", "<NAME>aterno", "Apellido Materno", "Telefono", "Calle", "Colonia", "Numero", "Provincia", "Correo" } )); jScrollPane1.setViewportView(jt_vista); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_barra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(129, 129, 129) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_datos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jl_icon_buscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(20, 20, 20)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_barra, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_icon_buscar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 241, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(51, 51, 51)) ); }// </editor-fold>//GEN-END:initComponents private void jb_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_guardarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jb_guardarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JScrollPane jScrollPane1; public javax.swing.JButton jb_eliminar; public javax.swing.JButton jb_guardar; public javax.swing.JButton jb_modificar; public javax.swing.JButton jb_nuevo; public javax.swing.JLabel jl_Provincia; public javax.swing.JLabel jl_ap_mat; public javax.swing.JLabel jl_ap_pat; public javax.swing.JLabel jl_calle; public javax.swing.JLabel jl_colonia; public javax.swing.JLabel jl_correo; public javax.swing.JLabel jl_eliminar; public javax.swing.JLabel jl_guadar; public javax.swing.JLabel jl_icon_buscar; public javax.swing.JLabel jl_id; public javax.swing.JLabel jl_imagen; public javax.swing.JLabel jl_modificar; public javax.swing.JLabel jl_nombre; public javax.swing.JLabel jl_nuevo; public javax.swing.JLabel jl_numero; public javax.swing.JLabel jl_telefono; public javax.swing.JLabel jl_titulo; public javax.swing.JPanel jp_barra; public javax.swing.JPanel jp_botones; public javax.swing.JPanel jp_datos; public javax.swing.JTable jt_vista; public javax.swing.JTextField jtf_ap_pat; public javax.swing.JTextField jtf_apt_mat; public javax.swing.JTextField jtf_buscar; public javax.swing.JTextField jtf_colonia; public javax.swing.JTextField jtf_correo; public javax.swing.JTextField jtf_id; public javax.swing.JTextField jtf_municipio; public javax.swing.JTextField jtf_nombre; public javax.swing.JTextField jtf_numero; public javax.swing.JTextField jtf_provincia; public javax.swing.JTextField jtf_telefono; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import conectar_tablas.Database; //llamamos la conexion a la BD para almacen import static conectar_tablas.Database.getConexion; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Octaviano */ public class modelVENTAS { //************************* Variables necesarias para compras ***************************** public String RFC_empleado; public String nombre_empleado;// solo se obtendra este dato, no se almacenara public String apellido_pat_empleado;// solo se obtendra este dato, no se almacenara public String apellido_mat_empleado;// solo se obtendra este dato, no se almacenara public int num_sucursal; //solo se obtendra este dato, no se almacenara. public String RFC_cliente; public String nombre_cliente; public String apell_pat_cliente; // solo se obtendra este dato, no se almacenara public String apell_mat_cliente; // solo se obtendra este dato, no se almacenara public int puntos_acumulados; public float subtotal; public float iva; public float importe; public int numero_venta; public String codigo_producto; public String codigo_producto_Promo; public String codigo_producto_Promo2; public String nombre_producto;// solo se obtendra este dato, no se almacenara public String tipo_producto;// solo se obtendra este dato, no se almacenara public String marca_producto;// solo se obtendra este dato, no se almacenara public String Status_producto; public String Status_vista; public int cantidad_venta = 1; //se incia la venta en uno public float precio_venta; public float precio_venta_promo; public Date fecha_final; public float total_por_producto=0.0f; public ArrayList producto; // la variable almacenara una lista para llenar comboBox public ArrayList numero_empleado; // la variable almacenara una lista para llenar comboBox public ArrayList numero_sucursal; // la variable almacenara una lista para llenar comboBox public ArrayList numero_cliente; // la variable almacenara una lista para llenar comboBox public ArrayList descuento_combo; // la variable almacenara una lista para llenar comboBox public int codigo_descuento; public int puntos_requeridos; public int cantidad_puntos; public int puntos; public int porcentaje; public float descuento; public float descuento_prod; public float efectivo; public String forma_pago; public float cambio; public int puntos_ganados; public String activo; public String getActivo() { return activo; } public void setActivo(String activo) { this.activo = activo; } public String getRFC_empleado() { return RFC_empleado; } public void setRFC_empleado(String RFC_empleado) { this.RFC_empleado = RFC_empleado; } public String getNombre_empleado() { return nombre_empleado; } public void setNombre_empleado(String nombre_empleado) { this.nombre_empleado = nombre_empleado; } public String getApellido_pat_empleado() { return apellido_pat_empleado; } public void setApellido_pat_empleado(String apellido_pat_empleado) { this.apellido_pat_empleado = apellido_pat_empleado; } public String getApellido_mat_empleado() { return apellido_mat_empleado; } public void setApellido_mat_empleado(String apellido_mat_empleado) { this.apellido_mat_empleado = apellido_mat_empleado; } public int getNum_sucursal() { return num_sucursal; } public void setNum_sucursal(int num_sucursal) { this.num_sucursal = num_sucursal; } public String getRFC_cliente() { return RFC_cliente; } public void setRFC_cliente(String RFC_cliente) { this.RFC_cliente = RFC_cliente; } public String getNombre_cliente() { return nombre_cliente; } public void setNombre_cliente(String nombre_cliente) { this.nombre_cliente = nombre_cliente; } public String getApell_pat_cliente() { return apell_pat_cliente; } public void setApell_pat_cliente(String apell_pat_cliente) { this.apell_pat_cliente = apell_pat_cliente; } public String getApell_mat_cliente() { return apell_mat_cliente; } public void setApell_mat_cliente(String apell_mat_cliente) { this.apell_mat_cliente = apell_mat_cliente; } public int getPuntos_acumulados() { return puntos_acumulados; } public void setPuntos_acumulados(int puntos_acumulados) { this.puntos_acumulados = puntos_acumulados; } public float getSubtotal() { return subtotal; } public void setSubtotal(float subtotal) { this.subtotal = subtotal; } public float getIva() { return iva; } public void setIva(float iva) { this.iva = iva; } public float getImporte() { return importe; } public void setImporte(float importe) { this.importe = importe; } public int getNumero_venta() { return numero_venta; } public void setNumero_venta(int numero_venta) { this.numero_venta = numero_venta; } public String getCodigo_producto() { return codigo_producto; } public void setCodigo_producto(String codigo_producto) { this.codigo_producto = codigo_producto; } public String getCodigo_producto_Promo() { return codigo_producto_Promo; } public void setCodigo_producto_Promo(String codigo_producto_Promo) { this.codigo_producto_Promo = codigo_producto_Promo; } public String getCodigo_producto_Promo2() { return codigo_producto_Promo2; } public void setCodigo_producto_Promo2(String codigo_producto_Promo2) { this.codigo_producto_Promo2 = codigo_producto_Promo2; } public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public String getTipo_producto() { return tipo_producto; } public void setTipo_producto(String tipo_producto) { this.tipo_producto = tipo_producto; } public String getMarca_producto() { return marca_producto; } public void setMarca_producto(String marca_producto) { this.marca_producto = marca_producto; } public String getStatus_producto() { return Status_producto; } public void setStatus_producto(String Status_producto) { this.Status_producto = Status_producto; } public String getStatus_vista() { return Status_vista; } public void setStatus_vista(String Status_vista) { this.Status_vista = Status_vista; } public int getCantidad_venta() { return cantidad_venta; } public void setCantidad_venta(int cantidad_venta) { this.cantidad_venta = cantidad_venta; } public float getPrecio_venta() { return precio_venta; } public float getPrecio_venta_promo() { return precio_venta_promo; } public void setPrecio_venta_promo(float precio_venta_promo) { this.precio_venta_promo = precio_venta_promo; } public Date getFecha_final() { return fecha_final; } public void setFecha_final(Date fecha_final) { this.fecha_final = fecha_final; } public void setPrecio_venta(float precio_venta) { this.precio_venta = precio_venta; } public float getTotal_por_producto() { return total_por_producto; } public void setTotal_por_producto(float total_por_producto) { this.total_por_producto = total_por_producto; } public int getCodigo_descuento() { return codigo_descuento; } public void setCodigo_descuento(int codigo_descuento) { this.codigo_descuento = codigo_descuento; } public int getPuntos_requeridos() { return puntos_requeridos; } public void setPuntos_requeridos(int puntos_requeridos) { this.puntos_requeridos = puntos_requeridos; } public int getCantidad_puntos() { return cantidad_puntos; } public void setCantidad_puntos(int cantidad_puntos) { this.cantidad_puntos = cantidad_puntos; } public int getPuntos() { return puntos; } public void setPuntos(int puntos) { this.puntos = puntos; } public int getPorcentaje() { return porcentaje; } public void setPorcentaje(int porcentaje) { this.porcentaje = porcentaje; } public float getDescuento() { return descuento; } public float getDescuento_prod() { return descuento_prod; } public void setDescuento_prod(float descuento_prod) { this.descuento_prod = descuento_prod; } public void setDescuento(float descuento) { this.descuento = descuento; } public float getEfectivo() { return efectivo; } public void setEfectivo(float efectivo) { this.efectivo = efectivo; } public String getForma_pago() { return forma_pago; } public void setForma_pago(String forma_pago) { this.forma_pago = forma_pago; } public float getCambio() { return cambio; } public void setCambio(float cambio) { this.cambio = cambio; } public int getPuntos_ganados() { return puntos_ganados; } public void setPuntos_ganados(int puntos_ganados) { this.puntos_ganados = puntos_ganados; } public ArrayList getProducto() { return producto; } public void setProducto(ArrayList producto) { this.producto = producto; } public ArrayList getNumero_empleado() { return numero_empleado; } public void setNumero_empleado(ArrayList numero_empleado) { this.numero_empleado = numero_empleado; } public ArrayList getNumero_sucursal() { return numero_sucursal; } public void setNumero_sucursal(ArrayList numero_sucursal) { this.numero_sucursal = numero_sucursal; } public ArrayList getNumero_cliente() { return numero_cliente; } public void setNumero_cliente(ArrayList numero_cliente) { this.numero_cliente = numero_cliente; } public ArrayList getDescuento_combo() { return descuento_combo; } public void setDescuento_combo(ArrayList descuento_combo) { this.descuento_combo = descuento_combo; } //**************Variables para conexion private Connection conexion; private Statement st; private ResultSet rs; PreparedStatement ps; public DefaultTableModel model_ventas = new DefaultTableModel(); public int rec;//Variable que tomara el valor seleccionado en la tabla public DefaultTableModel getModel_ventas() { return model_ventas; } public void setModel_ventas(DefaultTableModel model_ventas) { this.model_ventas = model_ventas; } public int getRec() { return rec; } public void setRec(int rec) { this.rec = rec; } //**********************ACTUALIZANDO STOCK***************************** public int stock_productos; public int stock_productos_sucursales; public int existencias_sucursal; public int existencia_general; public int getStock_productos() { return stock_productos; } public void setStock_productos(int stock_productos) { this.stock_productos = stock_productos; } public int getStock_productos_sucursales() { return stock_productos_sucursales; } public void setStock_productos_sucursales(int stock_productos_sucursales) { this.stock_productos_sucursales = stock_productos_sucursales; } public int getExistencias_sucursal() { return existencias_sucursal; } public void setExistencias_sucursal(int existencias_sucursal) { this.existencias_sucursal = existencias_sucursal; } public int getExistencia_general() { return existencia_general; } public void setExistencia_general(int existencia_general) { this.existencia_general = existencia_general; } /** * Conexion a la Base de datos */ public void Conectar() { try { conexion = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia", "root", ""); st = conexion.createStatement(); } catch (SQLException err) { JOptionPane.showMessageDialog(null, "Error " + err.getMessage()); } } /*** * el metodo que llenara los comboBox con los registros necesarios de la base de datos */ public void llenarCombo(){ //llenar comboBox de RFC empleados ArrayList rfc = new ArrayList(); try{ rs = st.executeQuery("SELECT * FROM empleados_ventas;"); }catch(SQLException e){ JOptionPane.showMessageDialog(null,"error1 al llenar comboBox"+e); } try{ while(rs.next()){ String empl=rs.getString("RFC_empl_vent"); rfc.add(empl);//agregar los datos a la lista }this.setNumero_empleado(rfc);// almacena la lista con los numeros de proveedores obetenidos de la BD }catch(Exception e){ JOptionPane.showMessageDialog(null,"error3 al llenar comboBox"+e); } ArrayList num_suc = new ArrayList(); // lista para sucursales //llenar comboBox de Sucursales try{ rs = st.executeQuery("SELECT * FROM sucursal;"); }catch(SQLException e){ JOptionPane.showMessageDialog(null,"error1 al llenar comboBox"+e); } try{ while(rs.next()){ String sucursal=rs.getString("no_sucursal"); num_suc.add(sucursal);//agregar los datos a la lista }this.setNumero_sucursal(num_suc);// almacena la lista con los numeros de proveedores obetenidos de la BD }catch(Exception e){ JOptionPane.showMessageDialog(null,"error2 al llenar comboBox"+e); } //llenar comboBox de codigo de productos ArrayList codigo = new ArrayList(); try{ rs = st.executeQuery("SELECT * FROM productos;"); }catch(SQLException e){ JOptionPane.showMessageDialog(null,"error4 al llenar comboBox"+e); } try{ while(rs.next()){ String prod=rs.getString("codigo_producto"); codigo.add(prod);//agregar los datos a la lista }this.setProducto(codigo);// almacena la lista con los numeros de proveedores obetenidos de la BD }catch(Exception e){ JOptionPane.showMessageDialog(null,"error5 al llenar comboBox"+e); } //llenar comboBox de RFC del cliente ArrayList cliente = new ArrayList(); try{ rs = st.executeQuery("SELECT * FROM clientes;"); }catch(SQLException e){ JOptionPane.showMessageDialog(null,"error4 al llenar comboBox"+e); } try{ while(rs.next()){ String client=rs.getString("RFC_cliente"); cliente.add(client);//agregar los datos a la lista }this.setNumero_cliente(cliente);// almacena la lista con los numeros de proveedores obetenidos de la BD }catch(Exception e){ JOptionPane.showMessageDialog(null,"error5 al llenar comboBox"+e); } //llenar comboBox de Descuentos ArrayList descuentos = new ArrayList(); try{ rs = st.executeQuery("SELECT * FROM descuentos;"); }catch(SQLException e){ JOptionPane.showMessageDialog(null,"error4 al llenar comboBox"+e); } try{ while(rs.next()){ String desc=rs.getString("codigo_descuento"); descuentos.add(desc);//agregar los datos a la lista }this.setDescuento_combo(descuentos);// almacena la lista con los numeros de proveedores obetenidos de la BD }catch(Exception e){ JOptionPane.showMessageDialog(null,"error5 al llenar comboBox"+e); } } /** * llenado de los TextFields con los datos que le correspondan * segun sea seleccionado en el comboBox */ public void llenarTextFieldsEmpleados(){ try{ RFC_empleado=this.getRFC_empleado(); rs = st.executeQuery("SELECT * FROM empleados_ventas WHERE RFC_empl_vent='" +RFC_empleado+ "';");//consulta a empleaddos ventas rs.next(); nombre_empleado = rs.getString("nombre_empl_vent"); apellido_pat_empleado = rs.getString("ap_pat_vent"); apellido_mat_empleado = rs.getString("ap_mat_vent"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error7 al llenarTextFields"+e); } } public void llenarTextFieldsClientes(){ try{ RFC_cliente=this.getRFC_cliente(); rs = st.executeQuery("SELECT * FROM clientes WHERE RFC_cliente='" +RFC_cliente+ "';");//consulta a clientes rs.next(); nombre_cliente = rs.getString("nombre_client"); apell_pat_cliente= rs.getString("ap_pat_client"); apell_mat_cliente = rs.getString("ap_mat_client"); puntos_acumulados=rs.getInt("puntos"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error8 al llenarTextFields"+e); } } public void llenarTextFieldsDescuentos(){ try{ codigo_descuento = this.getCodigo_descuento(); rs = st.executeQuery("SELECT * FROM descuentos WHERE codigo_descuento='" +codigo_descuento+ "';");//consulta a descuentos rs.next(); porcentaje = rs.getInt("porcentaje"); cantidad_puntos = rs.getInt("cantidad_puntos"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error9 al llenarTextFields"+e); } } /** * El metodo pasara a las variables correspondintes los datos de los productos * pasara los datos de los productos que esten el promocion * para poder ser utlizado en el controlador de ventas * verificara si la Promocion esta Vigente * verificara si el producto esta o no a la venta */ public void llenarTextFieldsProductos(){ try{//tabla de productos codigo_producto = this.getCodigo_producto(); rs = st.executeQuery("SELECT * FROM productos WHERE codigo_producto='"+codigo_producto+"';");//consulta a productos rs.next(); nombre_producto = rs.getString("nom_producto");// solo se obtendra este dato, no se almacenara tipo_producto = rs.getString("tipo_producto");// solo se obtendra este dato, no se almacenara marca_producto = rs.getString("marca"); precio_venta = rs.getFloat("precio_unitario_venta"); Status_producto=rs.getString("status_prod"); switch (Status_producto) { case "en venta": Status_vista = "Venta Normal"; break; case "ya no se maneja": Status_vista = "El producto ya no se maneja"; precio_venta=0.0f; break; } codigo_producto_Promo = this.getCodigo_producto(); rs = st.executeQuery("SELECT * FROM promociones inner join promocion_prod on promociones.id_promociones = promocion_prod.id_promociones WHERE promocion_prod.codigo_producto='"+codigo_producto_Promo+"';");//consulta a productos rs.next(); codigo_producto_Promo2 = rs.getString("codigo_producto"); if (codigo_producto.equals(codigo_producto_Promo2)){ fecha_final = rs.getDate("fecha_final");// solo se obtendra este dato, no se almacenara System.out.println("La fecha:"+fecha_final); } //Conocer si la promocion a un se aplica segun la fecha de vencimiento Date date = new Date(); //Obtenemos la fecha del sistema (Actual) DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//dando formato a la fecha System.out.println("Fecha Controlador: "+dateFormat.format(date)); //agregamos el formato a la fecha //Hacer la comparacion para saber si la promocion aun se aplica if(date.before(fecha_final)){ precio_venta =rs.getFloat("precio_descuento");// solo se obtendra este dato, no se almacenara Status_vista = "Producto en **Promocion**"; System.out.println("se aplica la promocion"); }else{ Status_vista = "Venta Normal"; } }catch(Exception e){ System.out.println("El producto no esta en promocion, o se vencio su promocion"); } } //******************** METODOS PARA REALIZAR LA VENTA *************************** /** * metodo para conocer que numero de Venta es el que sigue */ public void numeroVentas(){ try{ //obtener el nuemero de registros dentro de la base de datos rs=st.executeQuery("SELECT * from ventas;"); rs.last(); numero_venta=rs.getInt("id_ventas");//obetner el numero de compra a realizar numero_venta=numero_venta+1; }catch(Exception e){ JOptionPane.showMessageDialog(null,"error10 AgregarDatosCompras "+ e); } } // Calculando el total por producto vendido public void TotalProductoVendido(){ cantidad_venta = this.getCantidad_venta(); precio_venta = this.getPrecio_venta(); //Realizando la operacion para obtener el total por producto total_por_producto=cantidad_venta*precio_venta; } //LLenando la tabla con el producto que se va a comprar /** * los siguientes metodos realizaran los siguientes procesos * 1. pasaran cada dato ingresado para la compra en la tabla, llenado una lista de los productos comprados * 2. calcularan el importe, iva y subtotal de toda la compra en genera * 3. este metodo solo servira para dar vista de como se ve cada producto * con su respectivo precio y cantidad manejando tambien el Total final (SIN GUARDAR EN LA BASE DE DATOS) */ public void AgregarDatosVenta(){ model_ventas.setColumnIdentifiers(new Object[]{"Numero de Venta", "Codigo Producto", "Nombre Producto", "Marca","Precio", "Cantidad", "Total"}); String datos[] = new String[8]; datos[0] = Integer.toString(this.getNumero_venta()); datos[1] = this.getCodigo_producto(); datos[2] = this.getNombre_producto(); datos[3] = this.getMarca_producto(); datos[4] = Float.toString(this.getPrecio_venta()); datos[5] = Integer.toString(this.getCantidad_venta()); datos[6] = Float.toString(this.getTotal_por_producto()); model_ventas.addRow(datos); } /** * Calculando el importe de la Venta */ public void importe(){ //*********************calculando el importe, iva y subtotal de la compra*************** importe=this.getImporte(); iva= importe*16/100;//calculando el iva subtotal = importe - iva; //calculando el subtotal /** * Generar Puntos de acuerdo al importe generado y los puntos se generan para todos * los clientes, siempre y cuando no sea el cliente general */ RFC_cliente=this.getRFC_cliente(); if ("CLIENTEGENERA".equals(RFC_cliente)){ System.out.println("el cliente general no genera puntos"); }else{ puntos_ganados =(int)importe*3/100; //calcular los puntos ganados } } /** * Aplicando el descuento segun los puntos que el cliente tenga * el descuento se aplica en el importe final */ public void DescuentoImporte(){ llenarTextFieldsClientes(); llenarTextFieldsDescuentos(); if (puntos_acumulados >= cantidad_puntos){ // si los puntos del cliente son menores o iguales a los requeridos int confirmar = JOptionPane.showConfirmDialog(null, "¿esta seguro de realizar el descuento?"); if(JOptionPane.OK_OPTION==confirmar){ porcentaje = this.getPorcentaje(); importe = this.getImporte(); descuento = (porcentaje * importe)/100; descuento_prod = importe - descuento; //se aplica el descuento al importe final //volviando a calcular el iva y el subtotal iva= descuento_prod*16/100;//calculando el iva subtotal = descuento_prod - iva; //calculando el subtotal activo = "deshabilitado"; } }else { descuento_prod = importe; activo = "habilitado"; JOptionPane.showMessageDialog(null,"no se puede aplicar el descuento"); } } /*** * metodo que recibira el efectivo que da el cliente y de acuerdo al cliente * calculara cuanto debe de recibir de cambio * si el efectivo es menor al importe, no se puede realizar la operacion * de lo contrario la operacion se realizara con exito */ public void Cambio(){ try{ efectivo = this.getEfectivo(); if (efectivo > importe){ cambio = efectivo - importe; //se hace el calculo del cambio } }catch(Exception e){ System.out.println("error MODELO: ignorado, Cambio"); } } //************************* GUARDAR LA VENTA REALIZADA EN LA BASE DE DATOS ************************** /** * finalizar Venta * se hara la consulta a la base de datos, con las tablas de venta y detalle_venta * guardara en la tablas los datos que le corresponden a cada una * para realizar la venta y finalizarla */ /*** * Metodo que guradara en la tabla de ventas */ public void finalizarCompratablaVenta(){ int confirmar = JOptionPane.showConfirmDialog(null, "¿esta seguro de realizar la compra?"); if(JOptionPane.OK_OPTION==confirmar) { try{// se guarda en la tabla de compra Connection cn = getConexion(); RFC_cliente = this.getRFC_cliente(); subtotal = this.getSubtotal(); iva = this.getIva(); importe = this.getImporte(); numero_venta = this.getNumero_venta(); RFC_empleado = this.getRFC_empleado(); forma_pago= "Efectivo"; num_sucursal = this.getNum_sucursal(); codigo_descuento = this.getCodigo_descuento(); puntos_ganados = this.getPuntos_ganados(); ps = cn.prepareStatement("insert into ventas (RFC_cliente,subtotal_venta,iva,importe_vent,num_factura,RFC_empleado,forma_pago,no_sucursal,codigo_descuento,puntos_ganados)" + " values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"); ps.setString(1,RFC_cliente); ps.setFloat(2,subtotal); ps.setFloat(3,iva); ps.setFloat(4,importe); ps.setInt(5,numero_venta); ps.setString(6,RFC_empleado); ps.setString(7,forma_pago); ps.setInt(8,num_sucursal); ps.setInt(9,codigo_descuento); ps.setInt(10,puntos_ganados); ps.executeUpdate();//realizndo la accion de guardar }catch(Exception e){ JOptionPane.showMessageDialog(null,"error12 FinalizarVentas "+ e); } } } /** * este metodo guardara en la base de datos los datos correspondientes en detalle compra * 1. se le agrega a cada variable el valor correspondiente para despues agregarlo a la base de datos * 2. se hace la consulta para insertar datos */ public void finalizarCompratablaDetalleVenta(){ try{//se guardara en la tabla detalle_compra Connection cn = getConexion(); num_sucursal = this.getNum_sucursal(); numero_venta = this.getNumero_venta(); codigo_producto = this.getCodigo_producto(); cantidad_venta = this.getCantidad_venta(); precio_venta = this.getPrecio_venta(); total_por_producto = this.getTotal_por_producto(); ps = cn.prepareStatement("insert into detalle_ventas (id_ventas,codigo_producto,cantidad,precio_venta,total_producto)" + " values(?, ?, ?, ?, ?);"); ps.setInt(1,numero_venta); ps.setString(2,codigo_producto); ps.setFloat(3,cantidad_venta); ps.setFloat(4,precio_venta); ps.setFloat(5,total_por_producto); ps.executeUpdate();//realizndo la accion de guardar }catch(Exception e){ JOptionPane.showMessageDialog(null,"error13 FinalizarVentas "+ e); } } //*********************** ACTUALIZACION DE STOCK Y SUMAR Y RESTAR PUNTOS A USUARIOS *********************** /** * este metodo actuliza las existencias sumando a las exitencias actuales las nuevas * al relializar un compra, estos cambios se agregan en la tabla de sucursal_productos y en * productos que es la suma general de cada productos */ public void existencias(){ try{ //existencias por sucursal cantidad_venta = this.getCantidad_venta(); codigo_producto = this.getCodigo_producto(); num_sucursal = this.getNum_sucursal(); rs = st.executeQuery("SELECT * FROM sucursal_productos WHERE no_sucursal="+num_sucursal+" and codigo_producto='"+codigo_producto+"';");//consulta a sucursales_productos rs.next(); stock_productos_sucursales =rs.getInt("existencias"); existencias_sucursal = stock_productos_sucursales - cantidad_venta;//restando a existencias //revisar que los datos sean correctos System.out.println("sucursal:"+stock_productos_sucursales); System.out.println("sucursal:"+cantidad_venta); System.out.println("sucursal:"+existencias_sucursal); st.executeUpdate("UPDATE sucursal_productos SET existencias="+existencias_sucursal+" WHERE no_sucursal="+num_sucursal+" and codigo_producto='"+codigo_producto+"';"); //existencias generales en productos rs = st.executeQuery("SELECT * FROM productos WHERE codigo_producto='"+codigo_producto+"';");//consulta a productos rs.next(); stock_productos=rs.getInt("existencia_total"); //revisar que los datos sean correctos System.out.println("productos:"+stock_productos); System.out.println("productos:"+cantidad_venta); existencia_general = stock_productos - cantidad_venta; System.out.println(existencia_general); st.executeUpdate("UPDATE productos SET existencia_total="+existencia_general+" WHERE codigo_producto='"+codigo_producto+"';"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error16 FinalizarVentas "+ e); } } // ************* Sumando puntos generados a los Clientes **************** public void SumarPuntos(){ try{ RFC_cliente = this.getRFC_cliente(); rs = st.executeQuery("SELECT * FROM clientes WHERE RFC_cliente='"+RFC_cliente+"';");//consulta a productos rs.next(); cantidad_puntos=rs.getInt("puntos"); puntos = cantidad_puntos + puntos_ganados; st.executeUpdate("UPDATE clientes SET puntos= "+puntos+" WHERE RFC_cliente='"+RFC_cliente+"';"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error17 FinalizarVentas "+ e); } } /*** * metodo que realizara el llenado de la factura, haciendo el llenado de los * parametros correspendientes a la factura */ public void factura(){ try { Object[] opciones = {"aceptar","cancelar"}; int confirmar = JOptionPane.showConfirmDialog(null, "se realizara la factura?"); if (JOptionPane.OK_OPTION == confirmar){ } }catch(Exception e){ JOptionPane.showMessageDialog(null,"error al realizar la factura:"+ e); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewPromociones extends javax.swing.JPanel { /** * Creates new form ViewAgregarSucursal */ public ViewPromociones() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jp_titulo = new javax.swing.JPanel(); jl_titulo = new javax.swing.JLabel(); jl_buscar = new javax.swing.JLabel(); jtf_buscar = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jt_vista = new javax.swing.JTable(); jp_botones = new javax.swing.JPanel(); jb_nuevo = new javax.swing.JButton(); jl_nuevo = new javax.swing.JLabel(); jb_modificar = new javax.swing.JButton(); jl_modificar = new javax.swing.JLabel(); jb_eliminar = new javax.swing.JButton(); jl_eliminar = new javax.swing.JLabel(); jb_guardar = new javax.swing.JButton(); jl_guadar = new javax.swing.JLabel(); jp_datos1 = new javax.swing.JPanel(); jl_telefono1 = new javax.swing.JLabel(); jtf_numero1 = new javax.swing.JTextField(); jtf_telefono1 = new javax.swing.JTextField(); jl_no_sucursal1 = new javax.swing.JLabel(); jtf_no_promocion = new javax.swing.JTextField(); jtf_colonia1 = new javax.swing.JTextField(); jtf_causa = new javax.swing.JTextField(); jl_calle1 = new javax.swing.JLabel(); jl_numero1 = new javax.swing.JLabel(); jl_colonia1 = new javax.swing.JLabel(); jcb_buscar = new javax.swing.JComboBox<>(); jl_calle = new javax.swing.JLabel(); jl_colonia = new javax.swing.JLabel(); jDC_fe_inicio = new com.toedter.calendar.JDateChooser(); jDC_fe_final = new com.toedter.calendar.JDateChooser(); jp_productos = new javax.swing.JPanel(); jl_codigo_producto = new javax.swing.JLabel(); jl_nombre_producto = new javax.swing.JLabel(); jtf_nombre_producto = new javax.swing.JTextField(); jl_marca_producto = new javax.swing.JLabel(); jtf_marca_producto = new javax.swing.JTextField(); jcb_codigo_producto = new javax.swing.JComboBox<>(); jl_tipo_producto = new javax.swing.JLabel(); jtf_tipo_producto = new javax.swing.JTextField(); setBackground(new java.awt.Color(255, 255, 255)); setMaximumSize(new java.awt.Dimension(1059, 707)); setMinimumSize(new java.awt.Dimension(1059, 707)); setPreferredSize(new java.awt.Dimension(1059, 707)); setRequestFocusEnabled(false); jp_titulo.setBackground(new java.awt.Color(153, 204, 255)); jl_titulo.setFont(new java.awt.Font("Segoe UI", 0, 50)); // NOI18N jl_titulo.setForeground(new java.awt.Color(102, 102, 102)); jl_titulo.setText("Promociones"); javax.swing.GroupLayout jp_tituloLayout = new javax.swing.GroupLayout(jp_titulo); jp_titulo.setLayout(jp_tituloLayout); jp_tituloLayout.setHorizontalGroup( jp_tituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_tituloLayout.createSequentialGroup() .addContainerGap() .addComponent(jl_titulo) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_tituloLayout.setVerticalGroup( jp_tituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_titulo) ); jl_buscar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jl_buscar.setForeground(new java.awt.Color(102, 153, 255)); jl_buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jt_vista.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jt_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null} }, new String [] { "numero promocion", "causa", "descuento promocion", "costo con descuento", "unidad de medida", "codigo producto", "nombre del producto", "fecha inicio", "fecha final" } )); jScrollPane1.setViewportView(jt_vista); jp_botones.setBackground(new java.awt.Color(255, 255, 51)); jb_nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/nuevo.png"))); // NOI18N jl_nuevo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_nuevo.setForeground(new java.awt.Color(51, 51, 51)); jl_nuevo.setText("Nuevo"); jb_modificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Modificar.png"))); // NOI18N jl_modificar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_modificar.setForeground(new java.awt.Color(51, 51, 51)); jl_modificar.setText("Modificar"); jb_eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/eliminar.png"))); // NOI18N jl_eliminar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_eliminar.setForeground(new java.awt.Color(51, 51, 51)); jl_eliminar.setText("Eliminar"); jb_guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Guardar.png"))); // NOI18N jb_guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jb_guardarActionPerformed(evt); } }); jl_guadar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_guadar.setForeground(new java.awt.Color(51, 51, 51)); jl_guadar.setText("Guardar"); javax.swing.GroupLayout jp_botonesLayout = new javax.swing.GroupLayout(jp_botones); jp_botones.setLayout(jp_botonesLayout); jp_botonesLayout.setHorizontalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_botonesLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jl_nuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_modificar)) .addGap(18, 18, 18) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_guadar)) .addGap(26, 26, 26) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_eliminar)) .addGap(42, 42, 42)) ); jp_botonesLayout.setVerticalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jp_botonesLayout.createSequentialGroup() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_modificar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_modificar) .addComponent(jl_nuevo))) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jl_guadar)) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_botonesLayout.createSequentialGroup() .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jl_eliminar))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_datos1.setBackground(new java.awt.Color(255, 255, 255)); jp_datos1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos promocion", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 14), new java.awt.Color(0, 153, 255))); // NOI18N jl_telefono1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_telefono1.setForeground(new java.awt.Color(51, 51, 51)); jl_telefono1.setText("unidad de medida:"); jl_no_sucursal1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_no_sucursal1.setForeground(new java.awt.Color(51, 51, 51)); jl_no_sucursal1.setText("No. promocion:"); jtf_no_promocion.setEditable(false); jl_calle1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_calle1.setForeground(new java.awt.Color(51, 51, 51)); jl_calle1.setText("causa:"); jl_numero1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_numero1.setForeground(new java.awt.Color(51, 51, 51)); jl_numero1.setText("costo con descuento:"); jl_colonia1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_colonia1.setForeground(new java.awt.Color(51, 51, 51)); jl_colonia1.setText("descuento:"); javax.swing.GroupLayout jp_datos1Layout = new javax.swing.GroupLayout(jp_datos1); jp_datos1.setLayout(jp_datos1Layout); jp_datos1Layout.setHorizontalGroup( jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datos1Layout.createSequentialGroup() .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jp_datos1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jtf_causa, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datos1Layout.createSequentialGroup() .addGap(0, 18, Short.MAX_VALUE) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jp_datos1Layout.createSequentialGroup() .addComponent(jl_telefono1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_telefono1, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datos1Layout.createSequentialGroup() .addComponent(jl_numero1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_numero1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datos1Layout.createSequentialGroup() .addComponent(jl_colonia1) .addGap(196, 196, 196)) .addComponent(jtf_colonia1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datos1Layout.createSequentialGroup() .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_calle1) .addComponent(jl_no_sucursal1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_no_promocion, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(45, 45, 45))))) .addGap(27, 27, 27)) ); jp_datos1Layout.setVerticalGroup( jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datos1Layout.createSequentialGroup() .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_no_sucursal1) .addComponent(jtf_no_promocion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_causa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_calle1)) .addGap(18, 18, 18) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_colonia1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_colonia1)) .addGap(18, 18, 18) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_numero1) .addComponent(jtf_numero1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jp_datos1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_telefono1) .addComponent(jtf_telefono1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(13, Short.MAX_VALUE)) ); jcb_buscar.setBackground(new java.awt.Color(153, 204, 255)); jcb_buscar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jcb_buscar.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "codigo producto", "numero sucursal", " ", " " })); jl_calle.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_calle.setForeground(new java.awt.Color(51, 51, 51)); jl_calle.setText("fecha inicio:"); jl_colonia.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_colonia.setForeground(new java.awt.Color(51, 51, 51)); jl_colonia.setText("fecha final:"); jp_productos.setBackground(new java.awt.Color(255, 255, 255)); jp_productos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Producto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 12), new java.awt.Color(51, 153, 255))); // NOI18N jp_productos.setForeground(new java.awt.Color(51, 153, 255)); jl_codigo_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_codigo_producto.setText("Codigo producto:"); jl_nombre_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nombre_producto.setText("Nombre producto:"); jtf_nombre_producto.setEditable(false); jl_marca_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_marca_producto.setText(" Marca producto:"); jtf_marca_producto.setEditable(false); jcb_codigo_producto.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5" })); jl_tipo_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_tipo_producto.setText("Costo sin descuento:"); jtf_tipo_producto.setEditable(false); javax.swing.GroupLayout jp_productosLayout = new javax.swing.GroupLayout(jp_productos); jp_productos.setLayout(jp_productosLayout); jp_productosLayout.setHorizontalGroup( jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_productosLayout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jl_marca_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_marca_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jp_productosLayout.createSequentialGroup() .addGap(16, 16, 16) .addComponent(jl_codigo_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_codigo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(49, Short.MAX_VALUE)) .addGroup(jp_productosLayout.createSequentialGroup() .addComponent(jl_tipo_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_tipo_producto) .addGap(31, 31, 31)) .addGroup(jp_productosLayout.createSequentialGroup() .addContainerGap() .addComponent(jl_nombre_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_nombre_producto)) ); jp_productosLayout.setVerticalGroup( jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_productosLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_codigo_producto) .addComponent(jcb_codigo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nombre_producto) .addComponent(jtf_nombre_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_marca_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_marca_producto)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_tipo_producto) .addComponent(jtf_tipo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(14, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_titulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(jp_datos1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 296, Short.MAX_VALUE) .addComponent(jl_buscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcb_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jp_productos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jl_colonia) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jDC_fe_final, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jl_calle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jDC_fe_inicio, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGroup(layout.createSequentialGroup() .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_titulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcb_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jl_buscar)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_productos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDC_fe_inicio, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_calle)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_colonia) .addComponent(jDC_fe_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addComponent(jp_datos1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(68, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void jb_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_guardarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jb_guardarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public com.toedter.calendar.JDateChooser jDC_fe_final; public com.toedter.calendar.JDateChooser jDC_fe_inicio; public javax.swing.JScrollPane jScrollPane1; public javax.swing.JButton jb_eliminar; public javax.swing.JButton jb_guardar; public javax.swing.JButton jb_modificar; public javax.swing.JButton jb_nuevo; public javax.swing.JComboBox<String> jcb_buscar; public javax.swing.JComboBox<String> jcb_codigo_producto; private javax.swing.JLabel jl_buscar; public javax.swing.JLabel jl_calle; public javax.swing.JLabel jl_calle1; public javax.swing.JLabel jl_codigo_producto; public javax.swing.JLabel jl_colonia; public javax.swing.JLabel jl_colonia1; public javax.swing.JLabel jl_eliminar; public javax.swing.JLabel jl_guadar; public javax.swing.JLabel jl_marca_producto; public javax.swing.JLabel jl_modificar; public javax.swing.JLabel jl_no_sucursal1; public javax.swing.JLabel jl_nombre_producto; public javax.swing.JLabel jl_nuevo; public javax.swing.JLabel jl_numero1; public javax.swing.JLabel jl_telefono1; public javax.swing.JLabel jl_tipo_producto; public javax.swing.JLabel jl_titulo; public javax.swing.JPanel jp_botones; public javax.swing.JPanel jp_datos1; public javax.swing.JPanel jp_productos; private javax.swing.JPanel jp_titulo; public javax.swing.JTable jt_vista; public javax.swing.JTextField jtf_buscar; public javax.swing.JTextField jtf_causa; public javax.swing.JTextField jtf_colonia1; public javax.swing.JTextField jtf_marca_producto; public javax.swing.JTextField jtf_no_promocion; public javax.swing.JTextField jtf_nombre_producto; public javax.swing.JTextField jtf_numero1; public javax.swing.JTextField jtf_telefono1; public javax.swing.JTextField jtf_tipo_producto; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; import models.ModelDetalleCompras; import java.awt.Container; import java.sql.Date; import java.text.SimpleDateFormat; import javax.swing.JOptionPane; import views.ViewDetalleCompra; /** * * @author Ami */ public class ControllerDetalleCompra { public ModelDetalleCompras modelDetalleCompra; public ViewDetalleCompra viewDetalleCompra; MouseListener ml = new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewDetalleCompra.jT_detalle_compra) { jt_detalle_compra_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; KeyListener key = new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewDetalleCompra.jTF_busqueda) { modelDetalleCompra.setTrsFiltro(new TableRowSorter(viewDetalleCompra.jT_detalle_compra.getModel())); viewDetalleCompra.jT_detalle_compra.setRowSorter(modelDetalleCompra.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getSource() == viewDetalleCompra.jTF_busqueda) { modelDetalleCompra.setCadena(viewDetalleCompra.jTF_busqueda.getText()); viewDetalleCompra.jTF_busqueda.setText(modelDetalleCompra.getCadena()); filtro(); } } }; public ControllerDetalleCompra(ModelDetalleCompras modelDetalleCompra, ViewDetalleCompra viewDetalleCompra) { this.modelDetalleCompra = modelDetalleCompra; this.viewDetalleCompra = viewDetalleCompra; this.viewDetalleCompra.jT_detalle_compra.addMouseListener(ml);//agregar a la table el evento de MouseListener this.viewDetalleCompra.jTF_busqueda.addKeyListener(key); //agregar elevento de keylistener en la tabla ConexionBD(); //cajas_deshabilitadas(); mostrarProductos(); Vendedor(); } private void jt_detalle_compra_MouseClicked() { } /** * este metodo hace la conexion a la base de datos * llama a los metodos conectar, mostrar dentro del modelo * muestra en la tabla los datos que contiene la variable de modelo_sucursal */ public void ConexionBD(){ modelDetalleCompra.Conectar(); modelDetalleCompra.mostrar(); viewDetalleCompra.jT_detalle_compra.setModel(modelDetalleCompra.getModelo_detalle_compra()); //asignar a la tabla los valores correspondientes } // ********************************* M E T O D O D E B U S Q U E D A ******************************************* /*** * Metodo para filtar los datos de la busqueda */ public void filtro() { //depende del numero de items en el jcb if (viewDetalleCompra.jCB_buscar.getSelectedItem() == "RFC empleado") { modelDetalleCompra.setColumnaABuscar(2); //numero de columna en la tabla donde se encuentra el registro } else if (viewDetalleCompra.jCB_buscar.getSelectedItem() == "Codigo producto") { modelDetalleCompra.setColumnaABuscar(4); //numero de columna en la tabla donde se encuentra el registro } modelDetalleCompra.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewDetalleCompra.jTF_busqueda.getText(), modelDetalleCompra.getColumnaABuscar())); } private void cajas_deshabilitadas() { viewDetalleCompra.jTF_mejor_comprador.setEditable(false); viewDetalleCompra.jTF_prod_mas_comprado.setEditable(false); viewDetalleCompra.jTF_prod_menos_comprado.setEditable(false); } private void cajas_habilitadas() { viewDetalleCompra.jTF_mejor_comprador.setEditable(true); viewDetalleCompra.jTF_prod_mas_comprado.setEditable(true); viewDetalleCompra.jTF_prod_menos_comprado.setEditable(true); } //***************** BOTONES Ver, nuevo y Imprimir************************** /** * Metodo que limpiara las cajas de texto para ingresar nuevo datos. */ public void nuevo_DetalleVenta(){ //limpiar cada caja de la Interfaz viewDetalleCompra.jDC_fe_inicio.setCalendar(null); viewDetalleCompra.jTF_mejor_comprador.setText(modelDetalleCompra.getLimpiar()); viewDetalleCompra.jTF_prod_mas_comprado.setText(modelDetalleCompra.getLimpiar()); viewDetalleCompra.jTF_prod_menos_comprado.setText(modelDetalleCompra.getLimpiar()); cajas_habilitadas();//llamar al metodo de cajas habilitadas para proceder a escribir un nuevo registro } private void mostrarProductos(){ modelDetalleCompra.mostrarProducto(); modelDetalleCompra.mostrarProductoMenor(); viewDetalleCompra.jTF_prod_mas_comprado.setText(modelDetalleCompra.getNombre_producto()); viewDetalleCompra.jTF_prod_menos_comprado.setText(modelDetalleCompra.getProducto_menor()); } private void Vendedor(){ modelDetalleCompra.mostrarComprador(); viewDetalleCompra.jTF_mejor_comprador.setText(modelDetalleCompra.getNombre_empleado()+" "+modelDetalleCompra.getApellido_paterno()+" "+modelDetalleCompra.getApellido_materno()); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import models.ModelProveedoresEmpleados; import views.ViewProveedoresEmpleados; import views.ViewProveedoresEmpleados; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; /** * * @author Octaviano */ public class ControllerProveedoresEmpleados { ModelProveedoresEmpleados modelProveedoresEmpleados; ViewProveedoresEmpleados viewProveedoresEmpleados; ActionListener list = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewProveedoresEmpleados.jt_vista) { } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }; /** * Busar solo con un compo, no es necesario el metodo de filtro toda la * accion de buscar esta dentro del evento keyListener */ KeyListener key = new KeyListener() { @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewProveedoresEmpleados.jtf_buscar) { modelProveedoresEmpleados.setTrsFiltro(new TableRowSorter(viewProveedoresEmpleados.jt_vista.getModel())); viewProveedoresEmpleados.jt_vista.setRowSorter(modelProveedoresEmpleados.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { modelProveedoresEmpleados.setCadena(viewProveedoresEmpleados.jtf_buscar.getText()); viewProveedoresEmpleados.jtf_buscar.setText(modelProveedoresEmpleados.getCadena()); modelProveedoresEmpleados.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewProveedoresEmpleados.jtf_buscar.getText(), modelProveedoresEmpleados.getColumnaABuscar())); } }; public ControllerProveedoresEmpleados(ModelProveedoresEmpleados modelProveedoresEmpleados, ViewProveedoresEmpleados viewProveedoresEmpleados) { this.modelProveedoresEmpleados = modelProveedoresEmpleados; this.viewProveedoresEmpleados = viewProveedoresEmpleados; this.viewProveedoresEmpleados.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la caja e texto buscar this.viewProveedoresEmpleados.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener ConexionBD(); } public void ConexionBD() { modelProveedoresEmpleados.Conectar(); modelProveedoresEmpleados.mostrar(); viewProveedoresEmpleados.jt_vista.setModel(modelProveedoresEmpleados.getModelo_Proveedores()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked() { modelProveedoresEmpleados.setRec(viewProveedoresEmpleados.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import conectar_tablas.Database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; /** * * @author Octaviano */ public class ModelSucursalesEmpleados { DefaultTableModel modelo_sucursal = new DefaultTableModel(); //la variable modelo almacenara los tados de la tabla public DefaultTableModel getModelo_sucursal() { return modelo_sucursal; } public void setModelo_sucursal(DefaultTableModel modelo_sucursal) { this.modelo_sucursal = modelo_sucursal; } public int rec;//Variable que tomara el valor seleccionado en la tabla public int getRec() { return rec; } public void setRec(int rec) { this.rec = rec; } /** * Variables para el metodo de busqueda */ private TableRowSorter trsFiltro; // sirve para filtar los datos dentro de la tabla public TableRowSorter getTrsFiltro() { return trsFiltro; } public void setTrsFiltro(TableRowSorter trsFiltro) { this.trsFiltro = trsFiltro; } public int columnaABuscar; public String cadena; public String getCadena() { return cadena; } public void setCadena(String cadena) { this.cadena = cadena; } public int getColumnaABuscar() { return columnaABuscar; } public void setColumnaABuscar(int columnaABuscar) { this.columnaABuscar = columnaABuscar; } //Variables que corresponden a cada caja de texto public int verificar; public String sucursal; public String calle; public String colonia; public String numero; public String Telefono; public String codigo_producto; public String nombre_producto; public String stock; public String stock_maximo; public String Strock_minimo; public int getVerificar() { return verificar; } public void setVerificar(int verificar) { this.verificar = verificar; } public String getSucursal() { return sucursal; } public void setSucursal(String sucursal) { this.sucursal = sucursal; } public String getCalle() { return calle; } public void setCalle(String calle) { this.calle = calle; } public String getColonia() { return colonia; } public void setColonia(String colonia) { this.colonia = colonia; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getTelefono() { return Telefono; } public void setTelefono(String Telefono) { this.Telefono = Telefono; } public String getCodigo_producto() { return codigo_producto; } public void setCodigo_producto(String codigo_producto) { this.codigo_producto = codigo_producto; } public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public String getStock() { return stock; } public void setStock(String stock) { this.stock = stock; } public String getStock_maximo() { return stock_maximo; } public void setStock_maximo(String stock_maximo) { this.stock_maximo = stock_maximo; } public String getStrock_minimo() { return Strock_minimo; } public void setStrock_minimo(String Strock_minimo) { this.Strock_minimo = Strock_minimo; } //*************************Variables que corresponden a los BOTONES************************************* public String Limpiar = " "; public int codigo = 0; public String getLimpiar() { return Limpiar; } public void setLimpiar(String Limpiar) { this.Limpiar = Limpiar; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } DefaultTableModel model = new DefaultTableModel(); // variable que usa para el metodo de buscar public DefaultTableModel getModel() { return model; } public void setModel(DefaultTableModel model) { this.model = model; } private Connection conexion; private Statement st; private ResultSet rs; PreparedStatement ps; /** * se hace la conexion a la Base de datos y se hace la consulta hacia la * tabla de sucursales que tiene una union con la tabla de * sucursales_productos y finalmente con la tabla de produtos para obtener * el nombre del producto que se tiene en cada sucursal */ public void Conectar() { try { conexion =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia","root",""); //conexion = DriverManager.getConnection("jdbc:mysql://raspberry-tic41.zapto.org:3306/StockCia", "tic41", "tic41"); st = conexion.createStatement(); rs = st.executeQuery("SELECT sucursal.no_sucursal,productos.nom_producto, calle, colonia, numero, telefono,sucursal_productos.codigo_producto, existencias, limite_maximo, limite_minimo from sucursal inner join sucursal_productos on sucursal.no_sucursal = sucursal_productos.no_sucursal inner join productos on productos.codigo_producto = sucursal_productos.codigo_producto;"); rs.first(); } catch (SQLException err) { JOptionPane.showMessageDialog(null, "Error " + err.getMessage()); } } public void Guardar_Nuevo() { //cada variable obtendra el valor actual de las cajas de texto sucursal = this.getSucursal(); calle = this.getCalle(); colonia = this.getColonia(); numero = this.getTelefono(); codigo_producto = this.getCodigo_producto(); nombre_producto = this.getNombre_producto(); stock = this.getStock(); stock_maximo = this.getStock_maximo(); Strock_minimo = this.getStrock_minimo(); int confirmar = JOptionPane.showConfirmDialog(null, "¿Esta seguro de Guardar el NUEVO registro?"); if (JOptionPane.OK_OPTION == confirmar) { try { st.executeUpdate("insert into sucursal(no_sucursal,calle,colonia,numero,telefono) values" + "('" + sucursal + "','" + calle + "','" + colonia + "','" + numero + "','" + Telefono + "');"); JOptionPane.showMessageDialog(null, "Guardado con exito "); } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error Nuevo no se puede guardar " + err.getMessage()); } } } //nuevo public void Guardar_Modificado() { //cada variable obtendra el valor actual de las cajas de texto sucursal = this.getSucursal(); calle = this.getCalle(); colonia = this.getColonia(); numero = this.getTelefono(); codigo_producto = this.getCodigo_producto(); nombre_producto = this.getNombre_producto(); stock = this.getStock(); stock_maximo = this.getStock_maximo(); Strock_minimo = this.getStrock_minimo(); int confirmar = JOptionPane.showConfirmDialog(null, "¿Esta seguro de MODIFICAR registro?"); if (JOptionPane.OK_OPTION == confirmar) { try { st.executeUpdate("UPDATE sucursal SET calle='" + calle + "',colonia='" + colonia + "',numero='" + numero + "',telefono='" + Telefono + "',colonia='" + colonia + "',numero='" + numero + "'WHERE no_sucursal='" + sucursal + "';"); JOptionPane.showMessageDialog(null, "El registro se modifico correctamente"); } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error Nuevo no se puede guardar " + err.getMessage()); } } } public void mostrar() { ResultSet rs = Database.getTabla("SELECT sucursal.no_sucursal,productos.nom_producto, calle, colonia, numero, telefono,sucursal_productos.codigo_producto, existencias, limite_maximo, limite_minimo from sucursal inner join sucursal_productos on sucursal.no_sucursal = sucursal_productos.no_sucursal inner join productos on productos.codigo_producto = sucursal_productos.codigo_producto;"); modelo_sucursal.setColumnIdentifiers(new Object[]{"No sucursal", "Calle", "Colonia", "Numero", "Telefono", "Codigo_producto", "Nombre Producto", "Stock", "Stok maximo", "Stock minimo"}); try { while (rs.next()) { // añade los resultado a al modelo de tabla modelo_sucursal.addRow(new Object[]{rs.getString("sucursal.no_sucursal"), rs.getString("calle"), rs.getString("colonia"), rs.getString("numero"), rs.getString("telefono"), rs.getString("sucursal_productos.codigo_producto"), rs.getString("productos.nom_producto"), rs.getString("existencias"), rs.getString("limite_maximo"), rs.getString("limite_minimo")}); } } catch (Exception e) { System.out.println(e); } } //*****************METODOS DE BOTONES Nuevo, Borrar, Guardar y Modificar************************** } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import models.ModelCOMPRAS; import views.ViewCOMPRAS; /** * * @author Octaviano */ public class ControllerCOMPRAS { ModelCOMPRAS modelCOMPRAS; ViewCOMPRAS viewCOMPRAS; ActionListener list = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewCOMPRAS.jcb_numero_proveedor){ modelCOMPRAS.setId_proveedor(Integer.parseInt((String)viewCOMPRAS.jcb_numero_proveedor.getSelectedItem())); modelCOMPRAS.llenarTextFieldsProveedor(); viewCOMPRAS.jtf_nombre_proveedor.setText(modelCOMPRAS.getNombre_proveedor()+" "+modelCOMPRAS.getApell_pat_proveedor()+" "+modelCOMPRAS.getApell_mat_proveedor()); viewCOMPRAS.jtf_telefono_proveedor.setText(modelCOMPRAS.getTelefono_proveedor()); viewCOMPRAS.jcb_codigo_producto.setEnabled(true);//habilitando jcb productos }else if (e.getSource() == viewCOMPRAS.jcb_rfc){ modelCOMPRAS.setRFC_empleado((String) viewCOMPRAS.jcb_rfc.getSelectedItem()); modelCOMPRAS.llenarTextFieldsEmpleados(); viewCOMPRAS.jtf_nombre_empleado.setText(modelCOMPRAS.getNombre_empleado()+" "+modelCOMPRAS.getApellido_pat_empleado()+" "+modelCOMPRAS.getApellido_mat_empleado()); viewCOMPRAS.jcb_numero_sucursal.setEnabled(true);//habilitando jcb numero sucursal }else if (e.getSource() == viewCOMPRAS.jcb_codigo_producto){ modelCOMPRAS.setCodigo_producto((String) viewCOMPRAS.jcb_codigo_producto.getSelectedItem()); modelCOMPRAS.llenarTextFieldsProductos(); viewCOMPRAS.jtf_nombre_producto.setText(modelCOMPRAS.getNombre_producto()); viewCOMPRAS.jtf_tipo_producto.setText(modelCOMPRAS.getTipo_producto()); viewCOMPRAS.jtf_marca_producto.setText(modelCOMPRAS.getMarca_producto()); //habilitar cajas de texto viewCOMPRAS.jtf_cantidad.setEditable(true); viewCOMPRAS.jtf_precio.setEditable(true); //hablitar botones viewCOMPRAS.jb_agregar.setEnabled(true); viewCOMPRAS.jb_nuevo.setEnabled(false); }else if (e.getSource() == viewCOMPRAS.jcb_numero_sucursal){ viewCOMPRAS.jcb_numero_proveedor.setEnabled(true);//habilitando jcb numero de proveedor viewCOMPRAS.jb_nuevo.setEnabled(false); }else if (e.getSource() == viewCOMPRAS.jb_agregar){ llenadoTabla(); }else if (e.getSource() == viewCOMPRAS.jb_nuevo){ nuevo(); }else if (e.getSource() == viewCOMPRAS.jb_eliminar){ eliminar(); limpiarSinTabla(); }else if (e.getSource() == viewCOMPRAS.jb_modificar){ modificar(); limpiarSinTabla(); } else if (e.getSource() == viewCOMPRAS.jb_realizar_compra){ realizarCompra(); } } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewCOMPRAS.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; KeyListener key = new KeyListener(){ @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getSource() == viewCOMPRAS.jtf_cantidad || e.getSource() == viewCOMPRAS.jtf_precio){ TotalProducto(); } } }; public ControllerCOMPRAS(ModelCOMPRAS modelCOMPRAS, ViewCOMPRAS viewCOMPRAS) { this.modelCOMPRAS = modelCOMPRAS; this.viewCOMPRAS = viewCOMPRAS; viewCOMPRAS.jtf_cantidad.addKeyListener(key); viewCOMPRAS.jtf_precio.addKeyListener(key); this.viewCOMPRAS.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener modelCOMPRAS.Conectar();// conexion a la BD initComponents(); llenadoCombos(); setActionListener(); deshabiltarObjetos(); modelCOMPRAS.numeroCompras(); viewCOMPRAS.jtf_numero_compra.setText(Integer.toString(modelCOMPRAS.getNumero_compra())); viewCOMPRAS.jt_vista.setModel(modelCOMPRAS.getModel_compras());//agrenado modelo a la tabla } /** * se eliminan los Items de los comboBox */ public void initComponents(){ viewCOMPRAS.jcb_numero_proveedor.removeAllItems();//eliminar los items del comboBbx viewCOMPRAS.jcb_numero_sucursal.removeAllItems(); viewCOMPRAS.jcb_rfc.removeAllItems(); viewCOMPRAS.jcb_codigo_producto.removeAllItems(); } public void setActionListener(){ viewCOMPRAS.jcb_numero_proveedor.addActionListener(list); viewCOMPRAS.jcb_rfc.addActionListener(list); viewCOMPRAS.jcb_codigo_producto.addActionListener(list); viewCOMPRAS.jcb_numero_sucursal.addActionListener(list); //botones viewCOMPRAS.jb_agregar.addActionListener(list); viewCOMPRAS.jb_modificar.addActionListener(list); viewCOMPRAS.jb_nuevo.addActionListener(list); viewCOMPRAS.jb_realizar_compra.addActionListener(list); viewCOMPRAS.jb_eliminar.addActionListener(list); } public void llenadoCombos(){ modelCOMPRAS.llenarCombo(); for (int p = 0; p < modelCOMPRAS.getNumero_proveedor().size(); p++) { viewCOMPRAS.jcb_numero_proveedor.addItem((String) modelCOMPRAS.getNumero_proveedor().get(p)); } for (int s = 0; s < modelCOMPRAS.getNumero_sucursal().size(); s++) { viewCOMPRAS.jcb_numero_sucursal.addItem((String) modelCOMPRAS.getNumero_sucursal().get(s)); } for (int e = 0; e < modelCOMPRAS.getNumero_empleado().size(); e++) { viewCOMPRAS.jcb_rfc.addItem((String) modelCOMPRAS.getNumero_empleado().get(e)); } for (int c = 0; c < modelCOMPRAS.getProducto().size(); c++) { viewCOMPRAS.jcb_codigo_producto.addItem((String) modelCOMPRAS.getProducto().get(c)); } } /** * metodo que al haer clic en una fila de la tabla, pasara cada dato en sus Jtf correspondientes * para poder modificar o eliminar la fila seleccionada */ public void jt_vista_MouseClicked(){ modelCOMPRAS.setRec(viewCOMPRAS.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewCOMPRAS.jcb_codigo_producto.setSelectedItem(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 1).toString()); viewCOMPRAS.jtf_nombre_producto.setText(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 2).toString()); viewCOMPRAS.jtf_marca_producto.setText(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 3).toString()); viewCOMPRAS.jtf_precio.setText(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 4).toString()); viewCOMPRAS.jtf_cantidad.setText(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 5).toString()); viewCOMPRAS.jtf_total.setText(viewCOMPRAS.jt_vista.getValueAt(modelCOMPRAS.getRec(), 6).toString()); viewCOMPRAS.jb_modificar.setEnabled(true); viewCOMPRAS.jb_eliminar.setEnabled(true); viewCOMPRAS.jb_agregar.setEnabled(false); } /** * metodo que deshabilitara los combobox * para que no se pueda realizar otra accion, si no se ha registrado * quien va a hacer la compra (empleado) */ public void deshabiltarObjetos(){ viewCOMPRAS.jcb_numero_sucursal.setEnabled(false); viewCOMPRAS.jcb_numero_proveedor.setEnabled(false); viewCOMPRAS.jcb_codigo_producto.setEnabled(false); //Deshabilitar cajas de texto viewCOMPRAS.jtf_cantidad.setEditable(false); viewCOMPRAS.jtf_precio.setEditable(false); //Deshablitar botones viewCOMPRAS.jb_agregar.setEnabled(false); viewCOMPRAS.jb_modificar.setEnabled(false); viewCOMPRAS.jb_nuevo.setEnabled(false); viewCOMPRAS.jb_realizar_compra.setEnabled(false); viewCOMPRAS.jb_eliminar.setEnabled(false); //Deshabilitando la tabla de compras viewCOMPRAS.jt_vista.setEnabled(false); } public void TotalProducto(){ try{ modelCOMPRAS.setCantidad_compra(Integer.parseInt(viewCOMPRAS.jtf_cantidad.getText())); modelCOMPRAS.setPrecio_compra(Float.parseFloat(viewCOMPRAS.jtf_precio.getText())); modelCOMPRAS.TotalCompraProducto(); viewCOMPRAS.jtf_total.setText(Float.toString(modelCOMPRAS.getTotal_por_producto())); }catch(Exception e){ System.out.println("error ignorado Total Producto"); } } public void llenadoTabla(){ try{ viewCOMPRAS.jb_modificar.setEnabled(false); viewCOMPRAS.jb_nuevo.setEnabled(true); viewCOMPRAS.jb_eliminar.setEnabled(false); viewCOMPRAS.jb_realizar_compra.setEnabled(true); viewCOMPRAS.jcb_numero_sucursal.setEnabled(false); viewCOMPRAS.jcb_numero_proveedor.setEnabled(false); viewCOMPRAS.jcb_rfc.setEnabled(false); viewCOMPRAS.jb_agregar.setEnabled(false); viewCOMPRAS.jt_vista.setEnabled(true); modelCOMPRAS.setNumero_compra(Integer.parseInt(viewCOMPRAS.jtf_numero_compra.getText())); modelCOMPRAS.setCodigo_producto((String) viewCOMPRAS.jcb_codigo_producto.getSelectedItem()); modelCOMPRAS.setNombre_producto(viewCOMPRAS.jtf_nombre_producto.getText()); modelCOMPRAS.setMarca_producto(viewCOMPRAS.jtf_marca_producto.getText()); modelCOMPRAS.setPrecio_compra(Float.parseFloat(viewCOMPRAS.jtf_precio.getText())); modelCOMPRAS.setCantidad_compra(Integer.parseInt(viewCOMPRAS.jtf_cantidad.getText())); modelCOMPRAS.setTotal_por_producto(Float.parseFloat(viewCOMPRAS.jtf_total.getText())); modelCOMPRAS.AgregarDatosCompra(); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error11 AgregarDatosCompras "+ e); } //haciendo la suma de toda la columna de total por producto float fila=0; float total=0; for (int i = 0; i < viewCOMPRAS.jt_vista.getRowCount(); i++){ fila = Float.parseFloat(viewCOMPRAS.jt_vista.getValueAt(i,6).toString()); total += fila; } modelCOMPRAS.setImporte(total); modelCOMPRAS.importe(); viewCOMPRAS.jtf_importe.setText(Float.toString(modelCOMPRAS.getImporte())); viewCOMPRAS.jtf_iva.setText(Float.toString(modelCOMPRAS.getIva())); viewCOMPRAS.jtf_subtotal.setText(Float.toString(modelCOMPRAS.getSubtotal())); } /** * metodo para agregar un nuevo producto a compras * limpiara las cajas para poder agregar un nuevo producto */ public void limpiar(){ viewCOMPRAS.jtf_nombre_proveedor.setText(" "); viewCOMPRAS.jtf_telefono_proveedor.setText(" "); viewCOMPRAS.jtf_nombre_producto.setText(" "); viewCOMPRAS.jtf_tipo_producto.setText(" "); viewCOMPRAS.jtf_marca_producto.setText(" "); viewCOMPRAS.jtf_cantidad.setText("0"); viewCOMPRAS.jtf_precio.setText("0.0"); viewCOMPRAS.jtf_total.setText("0.0"); //LIMPIAR TABLA for (int i = 0; i < viewCOMPRAS.jt_vista.getRowCount(); i++) { modelCOMPRAS.getModel_compras().removeRow(i); i-=1; } } public void limpiarSinTabla(){ viewCOMPRAS.jtf_nombre_proveedor.setText(" "); viewCOMPRAS.jtf_telefono_proveedor.setText(" "); viewCOMPRAS.jtf_nombre_producto.setText(" "); viewCOMPRAS.jtf_tipo_producto.setText(" "); viewCOMPRAS.jtf_marca_producto.setText(" "); viewCOMPRAS.jtf_cantidad.setText("0"); viewCOMPRAS.jtf_precio.setText("0.0"); viewCOMPRAS.jtf_total.setText("0.0"); } public void nuevo(){ viewCOMPRAS.jtf_nombre_proveedor.setText(" "); viewCOMPRAS.jtf_telefono_proveedor.setText(" "); viewCOMPRAS.jtf_nombre_producto.setText(" "); viewCOMPRAS.jtf_tipo_producto.setText(" "); viewCOMPRAS.jtf_marca_producto.setText(" "); viewCOMPRAS.jtf_cantidad.setText("0"); viewCOMPRAS.jtf_precio.setText("0.0"); viewCOMPRAS.jtf_total.setText("0.0"); viewCOMPRAS.jb_agregar.setEnabled(false); viewCOMPRAS.jb_modificar.setEnabled(false); viewCOMPRAS.jb_eliminar.setEnabled(false); } /** * metodo que sirve para eliminar una fila seleccionda dentro de la tabla */ public void eliminar(){ modelCOMPRAS.getModel_compras().removeRow(viewCOMPRAS.jt_vista.getSelectedRow()); //eliina la fila seleccionada en la jtable //volviando a calcular el importe float fila=0; float total=0; for (int i = 0; i < viewCOMPRAS.jt_vista.getRowCount(); i++){ fila = Float.parseFloat(viewCOMPRAS.jt_vista.getValueAt(i,6).toString()); total += fila; } modelCOMPRAS.setImporte(total); modelCOMPRAS.importe(); viewCOMPRAS.jtf_importe.setText(Float.toString(modelCOMPRAS.getImporte())); viewCOMPRAS.jtf_iva.setText(Float.toString(modelCOMPRAS.getIva())); viewCOMPRAS.jtf_subtotal.setText(Float.toString(modelCOMPRAS.getSubtotal())); } /** * metodo que agregara el registro modificado * eliminara el dato que fue modificado */ public void modificar(){ eliminar(); llenadoTabla(); } /** * metodon que guardara cada dato de la compra en su respectiva tabla * en detalle compra, se agudaran los datos dentro de la jtable * en compra, se llenara con los datos de jos jtf que le corresponden a la tabla * este meodo finalizara toda la compra de la tabla */ public void realizarCompra(){ try{ // se guarda en Compras **agregando datos para guardar modelCOMPRAS.setId_proveedor(Integer.parseInt((String) viewCOMPRAS.jcb_numero_proveedor.getSelectedItem())); modelCOMPRAS.setImporte(Float.parseFloat(viewCOMPRAS.jtf_importe.getText())); modelCOMPRAS.setIva(Float.parseFloat(viewCOMPRAS.jtf_iva.getText())); modelCOMPRAS.setSubtotal(Float.parseFloat(viewCOMPRAS.jtf_subtotal.getText())); modelCOMPRAS.setNum_sucursal(Integer.parseInt((String) viewCOMPRAS.jcb_numero_sucursal.getSelectedItem())); modelCOMPRAS.finalizarCompratablaCompra();//llamamos al metodo de guardar en compra }catch(Exception e){ JOptionPane.showMessageDialog(null,"error14 FinalizarCompras "+ e); } //se guardara en detalle_compras ***agregando datos try{ for (int i = 0; i < viewCOMPRAS.jt_vista.getRowCount(); i++){ modelCOMPRAS.setNumero_compra(Integer.parseInt((String) viewCOMPRAS.jt_vista.getValueAt(i,0))); modelCOMPRAS.setCodigo_producto(viewCOMPRAS.jt_vista.getValueAt(i,1).toString()); modelCOMPRAS.setCantidad_compra(Integer.parseInt((String) viewCOMPRAS.jt_vista.getValueAt(i,5))); modelCOMPRAS.setPrecio_compra(Float.parseFloat((String) viewCOMPRAS.jt_vista.getValueAt(i,4))); modelCOMPRAS.setTotal_por_producto(Float.parseFloat((String)viewCOMPRAS.jt_vista.getValueAt(i,6))); modelCOMPRAS.finalizarCompratablaDetalleCompra(); //llamamos el metodo de guardar en detalle_compra } //Actualizar stock al realizar la compra for (int i = 0; i < viewCOMPRAS.jt_vista.getRowCount(); i++){ modelCOMPRAS.setNum_sucursal(Integer.parseInt((String) viewCOMPRAS.jcb_numero_sucursal.getSelectedItem())); modelCOMPRAS.setCodigo_producto(viewCOMPRAS.jt_vista.getValueAt(i,1).toString()); modelCOMPRAS.setCantidad_compra(Integer.parseInt((String) viewCOMPRAS.jt_vista.getValueAt(i,5))); modelCOMPRAS.existencias(); } JOptionPane.showMessageDialog(null,"Agregando compra"); JOptionPane.showMessageDialog(null,"Se realizo la compra con exito"); deshabiltarObjetos(); limpiar(); viewCOMPRAS.jcb_rfc.setEnabled(true); viewCOMPRAS.jtf_nombre_empleado.setText(" "); viewCOMPRAS.jtf_importe.setText("0.0"); viewCOMPRAS.jtf_iva.setText("0.0"); viewCOMPRAS.jtf_subtotal.setText("0.0"); modelCOMPRAS.numeroCompras(); viewCOMPRAS.jtf_numero_compra.setText(Integer.toString(modelCOMPRAS.getNumero_compra())); }catch(Exception e){ JOptionPane.showMessageDialog(null,"error15 FinalizarCompras "+ e); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewProductos extends javax.swing.JPanel { /** * Creates new form Clientes */ public ViewProductos() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jp_barra = new javax.swing.JPanel(); jl_titulo = new javax.swing.JLabel(); jl_imagen = new javax.swing.JLabel(); jl_icon_buscar = new javax.swing.JLabel(); jtf_buscar = new javax.swing.JTextField(); jp_datos = new javax.swing.JPanel(); jl_precio_unitario = new javax.swing.JLabel(); jtf_marca = new javax.swing.JTextField(); jtf_precio_unitario = new javax.swing.JTextField(); jl_codigo_prod = new javax.swing.JLabel(); jtf_nom_prod = new javax.swing.JTextField(); jl_Existencia = new javax.swing.JLabel(); jtf_tipo_prod = new javax.swing.JTextField(); jtf_unidad_medida = new javax.swing.JTextField(); jtf_codigo_prod = new javax.swing.JTextField(); jl_numero = new javax.swing.JLabel(); jl_tipo_prod = new javax.swing.JLabel(); jl_nom_prod = new javax.swing.JLabel(); jl_unidad_medida = new javax.swing.JLabel(); jl_status = new javax.swing.JLabel(); jl_existencia_total = new javax.swing.JLabel(); jl_descripcion = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); jta_descripcion = new javax.swing.JTextArea(); jl_image_producto = new javax.swing.JLabel(); jcb_status = new javax.swing.JComboBox<>(); jp_botones = new javax.swing.JPanel(); jb_nuevo = new javax.swing.JButton(); jl_nuevo = new javax.swing.JLabel(); jb_modificar = new javax.swing.JButton(); jl_modificar = new javax.swing.JLabel(); jb_eliminar = new javax.swing.JButton(); jl_eliminar = new javax.swing.JLabel(); jb_guardar = new javax.swing.JButton(); jl_guadar = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jt_vista = new javax.swing.JTable(); setBackground(new java.awt.Color(255, 255, 255)); jp_barra.setBackground(new java.awt.Color(153, 204, 255)); jl_titulo.setFont(new java.awt.Font("Segoe UI", 0, 50)); // NOI18N jl_titulo.setForeground(new java.awt.Color(102, 102, 102)); jl_titulo.setText("Productos"); jl_imagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/productos.png"))); // NOI18N javax.swing.GroupLayout jp_barraLayout = new javax.swing.GroupLayout(jp_barra); jp_barra.setLayout(jp_barraLayout); jp_barraLayout.setHorizontalGroup( jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_barraLayout.createSequentialGroup() .addGap(44, 44, 44) .addComponent(jl_titulo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jl_imagen) .addGap(61, 61, 61)) ); jp_barraLayout.setVerticalGroup( jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_barraLayout.createSequentialGroup() .addGroup(jp_barraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_imagen) .addComponent(jl_titulo)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jl_icon_buscar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jl_icon_buscar.setForeground(new java.awt.Color(0, 153, 204)); jl_icon_buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jl_icon_buscar.setText("Buscar por codigo..."); jp_datos.setBackground(new java.awt.Color(255, 255, 255)); jp_datos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 14), new java.awt.Color(0, 153, 255))); // NOI18N jl_precio_unitario.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_precio_unitario.setForeground(new java.awt.Color(51, 51, 51)); jl_precio_unitario.setText("Precio unitario:"); jtf_marca.setEditable(false); jtf_precio_unitario.setEditable(false); jl_codigo_prod.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_codigo_prod.setForeground(new java.awt.Color(51, 51, 51)); jl_codigo_prod.setText("Codigo Producto:"); jtf_nom_prod.setEditable(false); jl_Existencia.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_Existencia.setForeground(new java.awt.Color(51, 51, 51)); jl_Existencia.setText("Stock TOTAL:"); jtf_tipo_prod.setEditable(false); jtf_unidad_medida.setEditable(false); jtf_codigo_prod.setEditable(false); jl_numero.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_numero.setForeground(new java.awt.Color(51, 51, 51)); jl_numero.setText("Marca:"); jl_tipo_prod.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_tipo_prod.setForeground(new java.awt.Color(51, 51, 51)); jl_tipo_prod.setText("Tipo producto:"); jl_nom_prod.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nom_prod.setForeground(new java.awt.Color(51, 51, 51)); jl_nom_prod.setText("Nombre producto:"); jl_unidad_medida.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_unidad_medida.setForeground(new java.awt.Color(51, 51, 51)); jl_unidad_medida.setText("unidad medida:"); jl_status.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_status.setForeground(new java.awt.Color(51, 51, 51)); jl_status.setText("Status:"); jl_existencia_total.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jl_existencia_total.setForeground(new java.awt.Color(51, 153, 255)); jl_existencia_total.setText("0"); jl_descripcion.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_descripcion.setForeground(new java.awt.Color(51, 51, 51)); jl_descripcion.setText("descripcion:"); jta_descripcion.setEditable(false); jta_descripcion.setColumns(20); jta_descripcion.setRows(5); jScrollPane2.setViewportView(jta_descripcion); jl_image_producto.setBorder(javax.swing.BorderFactory.createTitledBorder("")); jcb_status.setBackground(new java.awt.Color(153, 204, 255)); jcb_status.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jcb_status.setForeground(new java.awt.Color(51, 51, 51)); jcb_status.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "en venta ", "ya no se maneja" })); javax.swing.GroupLayout jp_datosLayout = new javax.swing.GroupLayout(jp_datos); jp_datos.setLayout(jp_datosLayout); jp_datosLayout.setHorizontalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addGap(16, 16, 16) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_codigo_prod) .addComponent(jl_tipo_prod) .addComponent(jl_numero)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_codigo_prod, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_tipo_prod, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_marca, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_status) .addComponent(jl_unidad_medida)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtf_unidad_medida, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE) .addComponent(jcb_status, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_precio_unitario) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_precio_unitario, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGroup(jp_datosLayout.createSequentialGroup() .addContainerGap() .addComponent(jl_nom_prod) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_nom_prod, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(27, 27, 27) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_Existencia) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jl_existencia_total)) .addComponent(jl_descripcion)) .addGap(49, 49, 49) .addComponent(jl_image_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_datosLayout.setVerticalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_Existencia) .addComponent(jl_existencia_total)) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_codigo_prod) .addComponent(jtf_codigo_prod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(16, 16, 16))) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_nom_prod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_nom_prod)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_tipo_prod) .addComponent(jtf_tipo_prod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_marca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_numero)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_precio_unitario) .addComponent(jtf_precio_unitario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(jl_descripcion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_unidad_medida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_unidad_medida)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_status) .addComponent(jcb_status, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))) .addGap(0, 0, Short.MAX_VALUE)))) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jl_image_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jp_botones.setBackground(new java.awt.Color(255, 255, 51)); jb_nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/nuevo.png"))); // NOI18N jl_nuevo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_nuevo.setForeground(new java.awt.Color(51, 51, 51)); jl_nuevo.setText("Nuevo"); jb_modificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Modificar.png"))); // NOI18N jl_modificar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_modificar.setForeground(new java.awt.Color(51, 51, 51)); jl_modificar.setText("Modificar"); jb_eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/eliminar.png"))); // NOI18N jl_eliminar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_eliminar.setForeground(new java.awt.Color(51, 51, 51)); jl_eliminar.setText("Eliminar"); jb_guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Guardar.png"))); // NOI18N jl_guadar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_guadar.setForeground(new java.awt.Color(51, 51, 51)); jl_guadar.setText("Guardar"); javax.swing.GroupLayout jp_botonesLayout = new javax.swing.GroupLayout(jp_botones); jp_botones.setLayout(jp_botonesLayout); jp_botonesLayout.setHorizontalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_botonesLayout.createSequentialGroup() .addContainerGap(79, Short.MAX_VALUE) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jl_nuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(48, 48, 48) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_modificar)) .addGap(28, 28, 28) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_eliminar)) .addGap(34, 34, 34) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_guadar)) .addGap(88, 88, 88)) ); jp_botonesLayout.setVerticalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jp_botonesLayout.createSequentialGroup() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nuevo) .addComponent(jl_modificar) .addComponent(jl_eliminar) .addComponent(jl_guadar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jt_vista.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jt_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null} }, new String [] { "Codigo Producto", "Nombre Producto", "Tipo Producto", "Marca", "Precio Unitario", "Unidad de medida", "Status", "Stock Total", "Desripcion" } )); jScrollPane1.setViewportView(jt_vista); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_barra, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jp_datos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jl_icon_buscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(20, 20, 20)) .addGroup(layout.createSequentialGroup() .addGap(155, 155, 155) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_barra, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_icon_buscar)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; public javax.swing.JButton jb_eliminar; public javax.swing.JButton jb_guardar; public javax.swing.JButton jb_modificar; public javax.swing.JButton jb_nuevo; public javax.swing.JComboBox<String> jcb_status; public javax.swing.JLabel jl_Existencia; public javax.swing.JLabel jl_codigo_prod; public javax.swing.JLabel jl_descripcion; public javax.swing.JLabel jl_eliminar; public javax.swing.JLabel jl_existencia_total; public javax.swing.JLabel jl_guadar; public javax.swing.JLabel jl_icon_buscar; private javax.swing.JLabel jl_image_producto; public javax.swing.JLabel jl_imagen; public javax.swing.JLabel jl_modificar; public javax.swing.JLabel jl_nom_prod; public javax.swing.JLabel jl_nuevo; public javax.swing.JLabel jl_numero; public javax.swing.JLabel jl_precio_unitario; public javax.swing.JLabel jl_status; public javax.swing.JLabel jl_tipo_prod; public javax.swing.JLabel jl_titulo; public javax.swing.JLabel jl_unidad_medida; public javax.swing.JPanel jp_barra; public javax.swing.JPanel jp_botones; public javax.swing.JPanel jp_datos; public javax.swing.JTable jt_vista; public javax.swing.JTextArea jta_descripcion; public javax.swing.JTextField jtf_buscar; public javax.swing.JTextField jtf_codigo_prod; public javax.swing.JTextField jtf_marca; public javax.swing.JTextField jtf_nom_prod; public javax.swing.JTextField jtf_precio_unitario; public javax.swing.JTextField jtf_tipo_prod; public javax.swing.JTextField jtf_unidad_medida; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import models.*; // todos los modelos import views.*; //todas las vistas import main.*; //importamos todas la clases main /** * * @author Octaviano */ public class ControllerLogin { ViewMenuAdmin viewMenuAdmin; private final ModelLogin modelLogin; private final ViewLogin viewLogin; MenuAdmin admin; ViewMenuAdmin viewmenuAdmin; /** * Esta variable almacena las Vistas base * para poder utilizarlos dentro del mismo JFrame. */ private Object controllers[]; private ControllerMenuAdmin controllerMenuAdmin; private ControllerEmpleadosCompras controllerEmpleadosCompras; private ControllerEmpleadosVentas controllerEmpleados; /** * Controlador principal donde se un el modelo y controlador de cada menu prinipal * Recibe cada controlador de las vistas de los menus * dentro de este controlador se tiene el accesso a la programacion * en el controlador de cada menu * @param modelLogin * @param viewLogin * @param controllers */ public ControllerLogin(ModelLogin modelLogin, ViewLogin viewLogin /*, ViewMenuAdmin viewmenuAdmin*//*, viewMenuEmpleadoCompras viewMenuEmpleadoCompras, viewMenuEmpleadoVentas viewMenuEmpleadoVentas*/){ this.modelLogin = modelLogin; this.viewLogin = viewLogin; viewLogin.jb_aceptar.addActionListener(actionListener); //agrega el evento ActionListener viewLogin.jb_cancelar.addActionListener(actionListener); //agrega el evento ActionListener //this.controllers = controllers; initComponets(); } private void initComponets() { viewLogin.setTitle("LOGIN"); viewLogin.setLocationRelativeTo(null); viewLogin.setVisible(true); } private final ActionListener actionListener = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewLogin.jb_aceptar) { opciones(); }else if (e.getSource() == viewLogin.jb_cancelar) { viewLogin.setVisible(false); System.exit(0); } } }; public void opciones(){ if (viewLogin.jcb_tipo_admin.getSelectedItem() == "Administrador"){ modelLogin.muenuAdmin(); viewLogin.setVisible(false); //ocultar el login } else if (viewLogin.jcb_tipo_admin.getSelectedItem() == "Empleado Ventas"){ modelLogin.empleadosVentas(); viewLogin.setVisible(false); //ocultar el login } else if (viewLogin.jcb_tipo_admin.getSelectedItem() == "Empleado Compras"){ modelLogin.EmpleadosCompras(); viewLogin.setVisible(false); //ocultar el login } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import controllers.*; import views.*; /** * * @author Octaviano */ public class ModelLogin { /*** * Variables para el logeo de los usuarios, y accedan a la interfaz que les corresponda. */ public void muenuAdmin(){ ModelClientes modelClientes = new ModelClientes(); ViewClientes viewClientes = new ViewClientes(); ControllerClientes controllerClientes = new ControllerClientes(modelClientes, viewClientes); ModelEmpleadosCompras modelEmpleadosCompras = new ModelEmpleadosCompras(); ViewEmpleadosCompras viewEmpleadosCompras = new ViewEmpleadosCompras(); ControllerEmpleadosCompras controllerEmpleadosCompras = new ControllerEmpleadosCompras(modelEmpleadosCompras, viewEmpleadosCompras); ModelEmpleadosVentas modelEmpleadosVentas = new ModelEmpleadosVentas(); ViewEmpleadosVentas viewEmpleadosVentas = new ViewEmpleadosVentas(); ControllerEmpleadosVentas controllerEmpleadosVentas = new ControllerEmpleadosVentas(modelEmpleadosVentas, viewEmpleadosVentas); ModelProductos modelProductos = new ModelProductos(); ViewProductos viewProductos = new ViewProductos(); ControllerProductos controllerProductos = new ControllerProductos(modelProductos, viewProductos); ModelProveedores modelProveedores = new ModelProveedores(); ViewProveedores viewProveedores = new ViewProveedores(); ControllerProveedores controllerProveedores = new ControllerProveedores(modelProveedores, viewProveedores); ModelSucursales modelSucursales = new ModelSucursales(); ViewSucursales viewSucursales = new ViewSucursales(); ControllerSucursales controllerSucursales = new ControllerSucursales(modelSucursales, viewSucursales); ModelAgregarSucursal modelAgregarSucursal = new ModelAgregarSucursal(); ViewAgregarSucursal viewAgregarSucursal = new ViewAgregarSucursal(); ControllerAgregarSucursal controllerAgregarSucursal = new ControllerAgregarSucursal(modelAgregarSucursal, viewAgregarSucursal); ModelDetalleCompras modelDetalleCompras = new ModelDetalleCompras(); ViewDetalleCompra viewDetalleCompra = new ViewDetalleCompra(); ControllerDetalleCompra controllerDetalleCompra = new ControllerDetalleCompra(modelDetalleCompras, viewDetalleCompra); ModelDetalleVentas modelDetalleVentas = new ModelDetalleVentas(); ViewDetalleVentas viewDetalleVentas = new ViewDetalleVentas(); ControllerDetalleVentas controllerDetalleVenta = new ControllerDetalleVentas(modelDetalleVentas, viewDetalleVentas); ModelPromociones modelPromociones = new ModelPromociones(); ViewPromociones viewPromociones = new ViewPromociones(); ControllerPromociones controllerPromociones = new ControllerPromociones(modelPromociones, viewPromociones); ModelDescuentos modelDescuentos = new ModelDescuentos(); ViewDescuentos viewDescuentos = new ViewDescuentos(); ControllerDescuentos controllerDescuentos = new ControllerDescuentos(modelDescuentos, viewDescuentos); Object[] controllers = new Object[11]; controllers[0] = controllerClientes; controllers[1] = controllerEmpleadosCompras; controllers[2] = controllerEmpleadosVentas; controllers[3] = controllerProductos; controllers[4] = controllerProveedores; controllers[5] = controllerSucursales; controllers[6] = controllerAgregarSucursal; controllers[7] = controllerDetalleCompra; controllers[8] = controllerDetalleVenta; controllers[9] = controllerPromociones; controllers[10] = controllerDescuentos; ModelMenuAdmin modelMenuAdmin = new ModelMenuAdmin(); ViewMenuAdmin viewMenuAdmin = new ViewMenuAdmin(); ControllerMenuAdmin controllerMenuAdmin = new ControllerMenuAdmin(modelMenuAdmin, viewMenuAdmin, controllers); } public void EmpleadosCompras(){ ModelClientesEmpleados modelClientesEmpleados = new ModelClientesEmpleados(); ViewClientesEmpleados viewClientesEmpleados = new ViewClientesEmpleados(); ControllerClientesEmpleados controllerClientesEmpleados = new ControllerClientesEmpleados(modelClientesEmpleados, viewClientesEmpleados); ModelProductosEmpleados modelProductosEmpleados = new ModelProductosEmpleados(); ViewProductosEmpleados viewProductosEmpleados = new ViewProductosEmpleados(); ControllerProductosEmpleados controllerProductosEmpleados = new ControllerProductosEmpleados(modelProductosEmpleados, viewProductosEmpleados); ModelProveedoresEmpleados modelProveedoresEmpleados = new ModelProveedoresEmpleados(); ViewProveedoresEmpleados viewProveedoresEmpleados = new ViewProveedoresEmpleados(); ControllerProveedoresEmpleados controllerProveedoresEmpleados = new ControllerProveedoresEmpleados(modelProveedoresEmpleados, viewProveedoresEmpleados); ModelSucursalesEmpleados modelSucursalesEmpleados = new ModelSucursalesEmpleados (); ViewSucursalesEmpleados viewSucursalesEmpleados = new ViewSucursalesEmpleados (); ControllerSucursalesEmpleados controllerSucursalesEmpleados = new ControllerSucursalesEmpleados (modelSucursalesEmpleados , viewSucursalesEmpleados ); ModelCOMPRAS modelCOMPRAS = new ModelCOMPRAS(); ViewCOMPRAS viewCOMPRAS = new ViewCOMPRAS(); ControllerCOMPRAS controllerCOMPRAS = new ControllerCOMPRAS(modelCOMPRAS,viewCOMPRAS); Object[] controllers = new Object[6]; controllers[0] = controllerClientesEmpleados; controllers[1] = controllerProductosEmpleados; controllers[2] = controllerProveedoresEmpleados; controllers[3] = controllerSucursalesEmpleados; controllers[4] = controllerCOMPRAS; ModelMenuEmpleadoCompras modelMenuEmpleadoCompras = new ModelMenuEmpleadoCompras (); viewMenuEmpleadoCompras ViewMenuEmpleadoCompras = new viewMenuEmpleadoCompras(); ControllerMenuEmpleadoCompras controllerMenuEmpleadoCompras = new ControllerMenuEmpleadoCompras(modelMenuEmpleadoCompras,ViewMenuEmpleadoCompras,controllers); } public void empleadosVentas(){ ModelClientesEmpleados modelClientesEmpleados = new ModelClientesEmpleados(); ViewClientesEmpleados viewClientesEmpleados = new ViewClientesEmpleados(); ControllerClientesEmpleados controllerClientesEmpleados = new ControllerClientesEmpleados(modelClientesEmpleados, viewClientesEmpleados); ModelProductosEmpleados modelProductosEmpleados = new ModelProductosEmpleados(); ViewProductosEmpleados viewProductosEmpleados = new ViewProductosEmpleados(); ControllerProductosEmpleados controllerProductosEmpleados = new ControllerProductosEmpleados(modelProductosEmpleados, viewProductosEmpleados); ModelProveedoresEmpleados modelProveedoresEmpleados = new ModelProveedoresEmpleados(); ViewProveedoresEmpleados viewProveedoresEmpleados = new ViewProveedoresEmpleados(); ControllerProveedoresEmpleados controllerProveedoresEmpleados = new ControllerProveedoresEmpleados(modelProveedoresEmpleados, viewProveedoresEmpleados); ModelSucursalesEmpleados modelSucursalesEmpleados = new ModelSucursalesEmpleados (); ViewSucursalesEmpleados viewSucursalesEmpleados = new ViewSucursalesEmpleados (); ControllerSucursalesEmpleados controllerSucursalesEmpleados = new ControllerSucursalesEmpleados (modelSucursalesEmpleados , viewSucursalesEmpleados ); modelVENTAS modelVENTAS = new modelVENTAS (); ViewVENTAS viewVENTAS = new ViewVENTAS (); ControllerVENTAS controllerVENTAS = new ControllerVENTAS (modelVENTAS ,viewVENTAS ); Object[] controllers = new Object[6]; controllers[0] = controllerClientesEmpleados; controllers[1] = controllerProductosEmpleados; controllers[2] = controllerProveedoresEmpleados; controllers[3] = controllerSucursalesEmpleados; controllers[4] = controllerVENTAS ; ModelMenuEmpleadoVentas modelMenuEmpleadoVentas = new ModelMenuEmpleadoVentas (); viewMenuEmpleadoVentas ViewMenuEmpleadoVentas = new viewMenuEmpleadoVentas(); ControllerMenuEmpleadoVentas controllerMenuEmpleadoVentas = new ControllerMenuEmpleadoVentas(modelMenuEmpleadoVentas,ViewMenuEmpleadoVentas,controllers); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; import models.ModelSucursales; import views.ViewSucursales; /** * * @author Octaviano */ public class ControllerSucursales { public ModelSucursales modelSucursales; public ViewSucursales viewSucursales; MouseListener ml = new MouseListener(){ @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewSucursales.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; KeyListener key = new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewSucursales.jtf_buscar) { modelSucursales.setTrsFiltro(new TableRowSorter(viewSucursales.jt_vista.getModel())); viewSucursales.jt_vista.setRowSorter(modelSucursales.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getSource() == viewSucursales.jtf_buscar) { modelSucursales.setCadena(viewSucursales.jtf_buscar.getText()); viewSucursales.jtf_buscar.setText(modelSucursales.getCadena()); filtro(); } } }; public ControllerSucursales(ModelSucursales modelSucursales, ViewSucursales viewSucursales) { this.modelSucursales = modelSucursales; this.viewSucursales = viewSucursales; this.viewSucursales.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener this.viewSucursales.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la tabla ConexionBD(); cajas_deshabilitadas(); } /** * este metodo hace la conexion a la base de datos * llama a los metodos conectar, mostrar dentro del modelo * muestra en la tabla los datos que contiene la variable de modelo_sucursal */ public void ConexionBD(){ modelSucursales.Conectar(); modelSucursales.mostrar(); viewSucursales.jt_vista.setModel(modelSucursales.getModelo_sucursal()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked(){ cajas_deshabilitadas(); // cuando se haga clic en la tabla, las cajas se volveran a deshabilitar modelSucursales.setRec(viewSucursales.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewSucursales.jtf_no_sucursal.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 0).toString()); viewSucursales.jtf_calle.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 1).toString()); viewSucursales.jtf_colonia.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 2).toString()); viewSucursales.jtf_numero.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 3).toString()); viewSucursales.jtf_telefono.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 4).toString()); viewSucursales.jtf_codigo_prod.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 5).toString()); viewSucursales.jtf_nom_prod.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 6).toString()); viewSucursales.jtf_stock.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 7).toString()); viewSucursales.jtf_stock_max.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 8).toString()); viewSucursales.jtf_stock_min.setText(viewSucursales.jt_vista.getValueAt(modelSucursales.getRec(), 9).toString()); } // ********************************* M E T O D O D E B U S Q U E D A ******************************************* /*** * Metodo para filtar los datos de la busqueda */ public void filtro() { //depende del numero de items en el jcb if (viewSucursales.jcb_buscar.getSelectedItem() == "codigo producto") { modelSucursales.setColumnaABuscar(5); //numero de columna en la tabla donde se encuentra el registro } else if (viewSucursales.jcb_buscar.getSelectedItem() == "numero sucursal") { modelSucursales.setColumnaABuscar(0); //numero de columna en la tabla donde se encuentra el registro } modelSucursales.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewSucursales.jtf_buscar.getText(), modelSucursales.getColumnaABuscar())); } public void cajas_deshabilitadas(){ viewSucursales.jtf_calle.setEditable(false); viewSucursales.jtf_colonia.setEditable(false); viewSucursales.jtf_numero.setEditable(false); viewSucursales.jtf_telefono.setEditable(false); viewSucursales.jtf_codigo_prod.setEditable(false); viewSucursales.jtf_nom_prod.setEditable(false); viewSucursales.jtf_stock.setEditable(false); viewSucursales.jtf_stock_max.setEditable(false); viewSucursales.jtf_stock_min.setEditable(false); } public void cajas_habilitadas(){ viewSucursales.jtf_calle.setEditable(true); viewSucursales.jtf_colonia.setEditable(true); viewSucursales.jtf_numero.setEditable(true); viewSucursales.jtf_telefono.setEditable(true); viewSucursales.jtf_codigo_prod.setEditable(true); viewSucursales.jtf_nom_prod.setEditable(true); viewSucursales.jtf_stock.setEditable(true); viewSucursales.jtf_stock_max.setEditable(true); viewSucursales.jtf_stock_min.setEditable(true); } //***************** BOTONES Nuevo, Borrar, Guardar y Modificar************************** /** * Metodo que limpiara las cajas de texto para ingresar nuevo datos. */ public void nuevo_sucursales(){ //limpiar cada caja de la Interfaz viewSucursales.jtf_no_sucursal.setText(Integer.toString(modelSucursales.getCodigo()));// la caja de texto CODIGO_PRODUCTO recibe el valor de cero viewSucursales.jtf_calle.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_colonia.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_numero.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_telefono.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_codigo_prod.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_nom_prod.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_stock.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_stock_max.setText(modelSucursales.getLimpiar()); viewSucursales.jtf_stock_min.setText(modelSucursales.getLimpiar()); cajas_habilitadas();//llamar al metodo de cajas habilitadas para proceder a escribir un nuevo registro } public void modificar_sucursales(){ viewSucursales.jtf_colonia.setEditable(true); viewSucursales.jtf_numero.setEditable(true); viewSucursales.jtf_telefono.setEditable(true); viewSucursales.jtf_codigo_prod.setEditable(true); viewSucursales.jtf_nom_prod.setEditable(true); viewSucursales.jtf_stock.setEditable(true); viewSucursales.jtf_stock_max.setEditable(true); viewSucursales.jtf_stock_min.setEditable(true); } public void Guardar() { // si la variable verificar es igual a 0 se llama al metodo de guardar Nuevo if (modelSucursales.getVerificar() == 1) { // darle el valor a las variables modelSucursales.setSucursal(viewSucursales.jtf_no_sucursal.getText()); modelSucursales.setCalle(viewSucursales.jtf_calle.getText()); modelSucursales.setColonia(viewSucursales.jtf_colonia.getText()); modelSucursales.setNumero(viewSucursales.jtf_numero.getText()); modelSucursales.setTelefono(viewSucursales.jtf_telefono.getText()); modelSucursales.setCodigo_producto(viewSucursales.jtf_codigo_prod.getText()); modelSucursales.setNombre_producto(viewSucursales.jtf_nom_prod.getText()); modelSucursales.setStock(viewSucursales.jtf_stock.getText()); modelSucursales.setStock_maximo(viewSucursales.jtf_stock_max.getText()); modelSucursales.setStrock_minimo(viewSucursales.jtf_stock_min.getText()); modelSucursales.Guardar_Nuevo(); // metodo de insertar nuevo registro } else { // darle el valor a las variables modelSucursales.setSucursal(viewSucursales.jtf_no_sucursal.getText()); modelSucursales.setCalle(viewSucursales.jtf_calle.getText()); modelSucursales.setColonia(viewSucursales.jtf_colonia.getText()); modelSucursales.setNumero(viewSucursales.jtf_numero.getText()); modelSucursales.setTelefono(viewSucursales.jtf_telefono.getText()); modelSucursales.setCodigo_producto(viewSucursales.jtf_codigo_prod.getText()); modelSucursales.setNombre_producto(viewSucursales.jtf_nom_prod.getText()); modelSucursales.setStock(viewSucursales.jtf_stock.getText()); modelSucursales.setStock_maximo(viewSucursales.jtf_stock_max.getText()); modelSucursales.setStrock_minimo(viewSucursales.jtf_stock_min.getText()); modelSucursales.Guardar_Modificado();// metodo de Modificar el registro } //LIMPIAR TABLA for (int i = 0; i < viewSucursales.jt_vista.getRowCount(); i++) { modelSucursales.getModelo_sucursal().removeRow(i); i -= 1; } //mostrar los nuevos datos modelSucursales.mostrar(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; import models.ModelProductos; import views.ViewProductos; /** * * @author Octaviano */ public class ControllerProductos { public ModelProductos modelProductos; public ViewProductos viewProductos; ActionListener list = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewProductos.jb_nuevo) { nuevo_productos(); }else if (e.getSource() == viewProductos.jb_modificar) { modificar_productos(); }else if (e.getSource() == viewProductos.jb_guardar) { Guardar(); } } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewProductos.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; /** * Busar solo con un compo, no es necesario el metodo de filtro * toda la accion de buscar esta dentro del evento keyListener */ KeyListener key = new KeyListener(){ @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewProductos.jtf_buscar) { modelProductos.setTrsFiltro(new TableRowSorter(viewProductos.jt_vista.getModel())); viewProductos.jt_vista.setRowSorter(modelProductos.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { modelProductos.setCadena(viewProductos.jtf_buscar.getText()); viewProductos.jtf_buscar.setText(modelProductos.getCadena()); modelProductos.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewProductos.jtf_buscar.getText(), modelProductos.getColumnaABuscar())); } }; public ControllerProductos(ModelProductos modelProductos, ViewProductos viewProductos) { this.modelProductos = modelProductos; this.viewProductos = viewProductos; this.viewProductos.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener this.viewProductos.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la caja e texto buscar viewProductos.jb_guardar.setEnabled(false);//El boton guardar aparecera inhabilitado viewProductos.jb_eliminar.setEnabled(false);//El boton guardar aparecera inhabilitado ConexionBD(); //se llama a este metodo para obtener los datos en la tabla cajas_deshabilitadas(); setActionListener(); } /*** * agregar eventos de actionlistener a botones */ private void setActionListener(){ viewProductos.jb_nuevo.addActionListener(list); viewProductos.jb_modificar.addActionListener(list); viewProductos.jb_guardar.addActionListener(list); } /** * este metodo hace la conexion a la base de datos * llama a los metodos conectar, mostrar dentro del modelo * muestra en la tabla los datos que contiene la variable de modelo_productos */ public void ConexionBD(){ modelProductos.Conectar(); modelProductos.mostrar(); viewProductos.jt_vista.setModel(modelProductos.getModelo_productos()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked(){ viewProductos.jb_guardar.setEnabled(false); viewProductos.jb_modificar.setEnabled(true);//El boton modificar aparecera habilitado viewProductos.jb_nuevo.setEnabled(true);//El boton nuevo aparecera habilitado cajas_deshabilitadas(); modelProductos.setRec(viewProductos.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewProductos.jtf_codigo_prod.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 0).toString()); viewProductos.jtf_nom_prod.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 1).toString()); viewProductos.jtf_tipo_prod.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 2).toString()); viewProductos.jtf_marca.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 3).toString()); viewProductos.jtf_precio_unitario.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 4).toString()); viewProductos.jtf_unidad_medida.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 5).toString()); viewProductos.jcb_status.setSelectedItem(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 6).toString()); viewProductos.jl_existencia_total.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 7).toString()); viewProductos.jta_descripcion.setText(viewProductos.jt_vista.getValueAt(modelProductos.getRec(), 8).toString()); } /*** * Metodos Habilitar y deshabilitar cajas */ public void cajas_deshabilitadas(){ viewProductos.jtf_codigo_prod.setEditable(false); viewProductos.jtf_nom_prod.setEditable(false); viewProductos.jtf_tipo_prod.setEditable(false); viewProductos.jtf_marca.setEditable(false); viewProductos.jtf_precio_unitario.setEditable(false); viewProductos.jtf_nom_prod.setEditable(false); viewProductos.jtf_unidad_medida.setEditable(false); viewProductos.jcb_status.setEditable(false); viewProductos.jta_descripcion.setEditable(false); } public void cajas_habilitadas(){ viewProductos.jtf_codigo_prod.setEditable(true); viewProductos.jtf_nom_prod.setEditable(true); viewProductos.jtf_tipo_prod.setEditable(true); viewProductos.jtf_marca.setEditable(true); viewProductos.jtf_precio_unitario.setEditable(true); viewProductos.jtf_nom_prod.setEditable(true); viewProductos.jtf_unidad_medida.setEditable(true); viewProductos.jcb_status.setEditable(true); viewProductos.jta_descripcion.setEditable(true); } //***************** BOTONES Nuevo, Borrar, Guardar y Modificar************************** public void nuevo_productos(){ viewProductos.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewProductos.jb_modificar.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelProductos.setVerificar(1);// le da el valor a verificar de cero para identificar un nuevo registro viewProductos.jtf_codigo_prod.setText(modelProductos.getLimpiar()); viewProductos.jtf_nom_prod.setText(modelProductos.getLimpiar()); viewProductos.jtf_tipo_prod.setText(modelProductos.getLimpiar()); viewProductos.jtf_marca.setText(modelProductos.getLimpiar()); viewProductos.jtf_precio_unitario.setText(modelProductos.getLimpiar()); viewProductos.jtf_nom_prod.setText(modelProductos.getLimpiar()); viewProductos.jtf_unidad_medida.setText(modelProductos.getLimpiar()); viewProductos.jta_descripcion.setText(modelProductos.getLimpiar()); viewProductos.jl_existencia_total.setText(Integer.toString(modelProductos.getCantidad())); cajas_habilitadas();//llamar al metodo de cajas habilitadas para proceder a escribir un nuevo registro } public void modificar_productos(){ viewProductos.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewProductos.jb_nuevo.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelProductos.setVerificar(2);// le da el valor a verificar de uno para identificar Modifiar registro viewProductos.jtf_codigo_prod.setEditable(false); // el codigo no se puede modificar viewProductos.jtf_nom_prod.setEditable(true); viewProductos.jtf_tipo_prod.setEditable(true); viewProductos.jtf_marca.setEditable(true); viewProductos.jtf_precio_unitario.setEditable(true); viewProductos.jtf_nom_prod.setEditable(true); viewProductos.jtf_unidad_medida.setEditable(true); viewProductos.jta_descripcion.setEditable(true); } public void Guardar(){ // si la variable verificar es igual a 0 se llama al metodo de guardar Nuevo if (modelProductos.getVerificar() == 1) { // darle el valor a las variables modelProductos.setCodigo_producto(viewProductos.jtf_codigo_prod.getText()); modelProductos.setNombre_producto(viewProductos.jtf_nom_prod.getText()); modelProductos.setTipo_producto(viewProductos.jtf_tipo_prod.getText()); modelProductos.setMarca(viewProductos.jtf_marca.getText()); modelProductos.setPrecio_unitario(Float.parseFloat(viewProductos.jtf_precio_unitario.getText())); modelProductos.setUnidad_medida(viewProductos.jtf_unidad_medida.getText()); modelProductos.setStatus((String) viewProductos.jcb_status.getSelectedItem()); modelProductos.setDescripcion(viewProductos.jta_descripcion.getText()); modelProductos.Guardar_Nuevo(); // metodo de insertar nuevo registro } else{ // darle el valor a las variables modelProductos.setCodigo_producto(viewProductos.jtf_codigo_prod.getText()); modelProductos.setNombre_producto(viewProductos.jtf_nom_prod.getText()); modelProductos.setTipo_producto(viewProductos.jtf_tipo_prod.getText()); modelProductos.setMarca(viewProductos.jtf_marca.getText()); modelProductos.setPrecio_unitario(Float.parseFloat(viewProductos.jtf_precio_unitario.getText())); modelProductos.setUnidad_medida(viewProductos.jtf_unidad_medida.getText()); modelProductos.setStatus((String) viewProductos.jcb_status.getSelectedItem()); modelProductos.setDescripcion(viewProductos.jta_descripcion.getText()); modelProductos.Guardar_Modificado();// metodo de Modificar el registro } //LIMPIAR TABLA for (int i = 0; i < viewProductos.jt_vista.getRowCount(); i++) { modelProductos.getModelo_productos().removeRow(i); i-=1; } //mostrar los nuevos datos modelProductos.mostrar(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class viewMenuEmpleadoVentas extends javax.swing.JFrame { /** * Creates new form viewMenuEmpleado */ public viewMenuEmpleadoVentas() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem(); jl_CiaLogo = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jm_catalogos = new javax.swing.JMenu(); jmi_proveedores = new javax.swing.JMenuItem(); jmi_clientes = new javax.swing.JMenuItem(); jmi_sucursales = new javax.swing.JMenuItem(); jmi_productos = new javax.swing.JMenuItem(); jm_acciones = new javax.swing.JMenu(); jmi_ventas = new javax.swing.JMenuItem(); jmi_cotizacion = new javax.swing.JMenuItem(); jm_opciones = new javax.swing.JMenu(); jmi_salir = new javax.swing.JMenuItem(); jCheckBoxMenuItem1.setSelected(true); jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jl_CiaLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/CIA-Developers.png"))); // NOI18N jMenuBar1.setBackground(new java.awt.Color(102, 102, 102)); jMenuBar1.setPreferredSize(new java.awt.Dimension(88, 35)); jm_catalogos.setBackground(new java.awt.Color(255, 255, 102)); jm_catalogos.setForeground(new java.awt.Color(255, 255, 255)); jm_catalogos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/catalogos.png"))); // NOI18N jm_catalogos.setText("Catalogos"); jmi_proveedores.setBackground(new java.awt.Color(255, 255, 255)); jmi_proveedores.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Proveedores.png"))); // NOI18N jmi_proveedores.setText("Proveedores"); jm_catalogos.add(jmi_proveedores); jmi_clientes.setBackground(new java.awt.Color(255, 255, 255)); jmi_clientes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/clientes.png"))); // NOI18N jmi_clientes.setText("Clientes"); jm_catalogos.add(jmi_clientes); jmi_sucursales.setBackground(new java.awt.Color(255, 255, 255)); jmi_sucursales.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/sucursales.png"))); // NOI18N jmi_sucursales.setText("sucursales"); jm_catalogos.add(jmi_sucursales); jmi_productos.setBackground(new java.awt.Color(255, 255, 255)); jmi_productos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/productos.png"))); // NOI18N jmi_productos.setText("Productos"); jm_catalogos.add(jmi_productos); jMenuBar1.add(jm_catalogos); jm_acciones.setForeground(new java.awt.Color(255, 255, 255)); jm_acciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/acciones.png"))); // NOI18N jm_acciones.setText("Acciones"); jmi_ventas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Ventas.png"))); // NOI18N jmi_ventas.setText("VENTAS"); jm_acciones.add(jmi_ventas); jmi_cotizacion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Cotizar.png"))); // NOI18N jmi_cotizacion.setText("COTIZACION"); jm_acciones.add(jmi_cotizacion); jMenuBar1.add(jm_acciones); jm_opciones.setForeground(new java.awt.Color(255, 255, 255)); jm_opciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/opciones.png"))); // NOI18N jm_opciones.setText("Opciones"); jmi_salir.setBackground(new java.awt.Color(255, 255, 255)); jmi_salir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Salir.png"))); // NOI18N jmi_salir.setText("Salir"); jm_opciones.add(jmi_salir); jMenuBar1.add(jm_opciones); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(926, Short.MAX_VALUE) .addComponent(jl_CiaLogo) .addGap(20, 20, 20)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(422, Short.MAX_VALUE) .addComponent(jl_CiaLogo) .addGap(35, 35, 35)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(viewMenuEmpleadoVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(viewMenuEmpleadoVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(viewMenuEmpleadoVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(viewMenuEmpleadoVentas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new viewMenuEmpleadoVentas().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1; public javax.swing.JMenuBar jMenuBar1; private javax.swing.JLabel jl_CiaLogo; public javax.swing.JMenu jm_acciones; public javax.swing.JMenu jm_catalogos; public javax.swing.JMenu jm_opciones; public javax.swing.JMenuItem jmi_clientes; public javax.swing.JMenuItem jmi_cotizacion; public javax.swing.JMenuItem jmi_productos; public javax.swing.JMenuItem jmi_proveedores; public javax.swing.JMenuItem jmi_salir; public javax.swing.JMenuItem jmi_sucursales; public javax.swing.JMenuItem jmi_ventas; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Ami */ public class ViewDetalleVentas extends javax.swing.JPanel { /** * Creates new form ViewDetalleVentas */ public ViewDetalleVentas() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jP_Titulo = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jP_buqueda_general = new javax.swing.JPanel(); jL_fecha_inicial = new javax.swing.JLabel(); jL_fecha_final = new javax.swing.JLabel(); jDC_fecha_inicial = new com.toedter.calendar.JDateChooser(); jDC_fehca_final = new com.toedter.calendar.JDateChooser(); jB_ver = new javax.swing.JButton(); jB_imprimir = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); jT_vista = new javax.swing.JTable(); jTF_busqueda = new javax.swing.JTextField(); jCB_buscar = new javax.swing.JComboBox<>(); jLabel4 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jL_mejor_vendedor = new javax.swing.JLabel(); jTF_mejor_vendedor = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jL_producto_mas_vendido = new javax.swing.JLabel(); jTF_prod_mas_vendido = new javax.swing.JTextField(); jL_producto_menos_vendido = new javax.swing.JLabel(); jTF_prod_menos_vendido = new javax.swing.JTextField(); setBackground(new java.awt.Color(255, 255, 255)); setPreferredSize(new java.awt.Dimension(1150, 692)); jP_Titulo.setBackground(new java.awt.Color(153, 204, 255)); jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 45)); // NOI18N jLabel1.setForeground(new java.awt.Color(102, 102, 102)); jLabel1.setText("Detalle Ventas"); javax.swing.GroupLayout jP_TituloLayout = new javax.swing.GroupLayout(jP_Titulo); jP_Titulo.setLayout(jP_TituloLayout); jP_TituloLayout.setHorizontalGroup( jP_TituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jP_TituloLayout.createSequentialGroup() .addGap(37, 37, 37) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jP_TituloLayout.setVerticalGroup( jP_TituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jP_TituloLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 11), new java.awt.Color(0, 153, 255))); // NOI18N jPanel1.setPreferredSize(new java.awt.Dimension(1307, 170)); jP_buqueda_general.setBackground(new java.awt.Color(255, 255, 255)); jP_buqueda_general.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Busqueda General", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 11), new java.awt.Color(0, 153, 255))); // NOI18N jL_fecha_inicial.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jL_fecha_inicial.setText("Fecha inicio (dia/mes/año) :"); jL_fecha_final.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jL_fecha_final.setText("Fecha final (dia/mes/año) :"); jB_ver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jB_ver.setText("Ver"); jB_imprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Botonimpirmi.png"))); // NOI18N jB_imprimir.setText("Imprimir"); javax.swing.GroupLayout jP_buqueda_generalLayout = new javax.swing.GroupLayout(jP_buqueda_general); jP_buqueda_general.setLayout(jP_buqueda_generalLayout); jP_buqueda_generalLayout.setHorizontalGroup( jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jP_buqueda_generalLayout.createSequentialGroup() .addGroup(jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jP_buqueda_generalLayout.createSequentialGroup() .addGap(54, 54, 54) .addComponent(jL_fecha_inicial) .addGap(87, 87, 87) .addComponent(jL_fecha_final)) .addGroup(jP_buqueda_generalLayout.createSequentialGroup() .addGap(62, 62, 62) .addComponent(jDC_fecha_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(107, 107, 107) .addComponent(jDC_fehca_final, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 66, Short.MAX_VALUE) .addGroup(jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jB_imprimir) .addComponent(jB_ver)) .addGap(18, 18, 18)) ); jP_buqueda_generalLayout.setVerticalGroup( jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jP_buqueda_generalLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jL_fecha_inicial) .addComponent(jL_fecha_final) .addComponent(jB_ver)) .addGap(22, 22, 22) .addGroup(jP_buqueda_generalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jDC_fehca_final, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jDC_fecha_inicial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jB_imprimir)) .addGap(19, 19, 19)) ); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(230, 230, 230) .addComponent(jP_buqueda_general, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jP_buqueda_general, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 6, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(255, 255, 51)); jPanel2.setPreferredSize(new java.awt.Dimension(1150, 692)); jT_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null, null, null} }, new String [] { "Id venta", "Fecha", "RFC cliente", "RFC empleado", "No sucursal", "Codigo descuento", "Puntos ganados", "Id detalle venta", "Codigo producto", "Cantidad", "Precio venta", "Total" } )); jScrollPane2.setViewportView(jT_vista); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 150, Short.MAX_VALUE) .addContainerGap()) ); jCB_buscar.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Seleccione uno", "RFC cliente", "RFC empleado", "Sucursal" })); jCB_buscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jCB_buscarActionPerformed(evt); } }); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Los mas destacado", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 11), new java.awt.Color(0, 153, 255))); // NOI18N jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/empleadoDestacado.png"))); // NOI18N jL_mejor_vendedor.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jL_mejor_vendedor.setText("Mejor Vendedor:"); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/productoMasVendido.png"))); // NOI18N jL_producto_mas_vendido.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jL_producto_mas_vendido.setText("Producto mas vendido: "); jL_producto_menos_vendido.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jL_producto_menos_vendido.setText("Producto menos vendido:"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel8) .addGap(41, 41, 41) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jL_mejor_vendedor) .addComponent(jTF_mejor_vendedor, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(57, 57, 57) .addComponent(jLabel9) .addGap(51, 51, 51) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jL_producto_mas_vendido) .addComponent(jTF_prod_mas_vendido, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(53, 53, 53) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTF_prod_menos_vendido, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jL_producto_menos_vendido)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jL_mejor_vendedor) .addGap(18, 18, 18) .addComponent(jTF_mejor_vendedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel8)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(7, 7, 7))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jL_producto_menos_vendido) .addComponent(jL_producto_mas_vendido)) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTF_prod_menos_vendido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTF_prod_mas_vendido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jP_Titulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(797, 797, 797) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jCB_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jTF_busqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(22, Short.MAX_VALUE)) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1150, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jP_Titulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jCB_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTF_busqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel4)) .addGap(7, 7, 7) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void jCB_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCB_buscarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jCB_buscarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JButton jB_imprimir; public javax.swing.JButton jB_ver; public javax.swing.JComboBox<String> jCB_buscar; public com.toedter.calendar.JDateChooser jDC_fecha_inicial; public com.toedter.calendar.JDateChooser jDC_fehca_final; private javax.swing.JLabel jL_fecha_final; private javax.swing.JLabel jL_fecha_inicial; private javax.swing.JLabel jL_mejor_vendedor; private javax.swing.JLabel jL_producto_mas_vendido; private javax.swing.JLabel jL_producto_menos_vendido; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jP_Titulo; private javax.swing.JPanel jP_buqueda_general; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane2; public javax.swing.JTextField jTF_busqueda; public javax.swing.JTextField jTF_mejor_vendedor; public javax.swing.JTextField jTF_prod_mas_vendido; public javax.swing.JTextField jTF_prod_menos_vendido; public javax.swing.JTable jT_vista; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import conectar_tablas.Database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; /** * * @author Ami */ public class ModelDetalleVentas { /*** * VAriables para proudctos, el mejor empleado */ public String nombre_producto; public String producto_menor; public String nombre_empleado; public String apellido_paterno; public String apellido_materno; public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public String getProducto_menor() { return producto_menor; } public void setProducto_menor(String producto_menor) { this.producto_menor = producto_menor; } public String getNombre_empleado() { return nombre_empleado; } public void setNombre_empleado(String nombre_empleado) { this.nombre_empleado = nombre_empleado; } public String getApellido_paterno() { return apellido_paterno; } public void setApellido_paterno(String apellido_paterno) { this.apellido_paterno = apellido_paterno; } public String getApellido_materno() { return apellido_materno; } public void setApellido_materno(String apellido_materno) { this.apellido_materno = apellido_materno; } //la variable modelo almacenara los tados de la tabla DefaultTableModel modelo_detalle_ventas = new DefaultTableModel(); public DefaultTableModel getModelo_detalle_ventas() { return modelo_detalle_ventas; } public void setModelo_detalle_ventas(DefaultTableModel modelo_detalle_ventas) { this.modelo_detalle_ventas = modelo_detalle_ventas; } public int rec;//Variable que tomara el valor seleccionado en la tabla public int getRec() { return rec; } public void setRec(int rec) { this.rec = rec; } public String Limpiar = " "; public String getLimpiar() { return Limpiar; } public void setLimpiar(String Limpiar) { this.Limpiar = Limpiar; } public int date; public int getDate() { return date; } public void setDate(int date) { this.date = date; } /** * Variables para el metodo de busqueda */ private TableRowSorter trsFiltro; // sirve para filtar los datos dentro de la tabla public TableRowSorter getTrsFiltro() { return trsFiltro; } public void setTrsFiltro(TableRowSorter trsFiltro) { this.trsFiltro = trsFiltro; } public int columnaABuscar; public String cadena; public int getColumnaABuscar() { return columnaABuscar; } public void setColumnaABuscar(int columnaABuscar) { this.columnaABuscar = columnaABuscar; } public String getCadena() { return cadena; } public void setCadena(String cadena) { this.cadena = cadena; } DefaultTableModel model = new DefaultTableModel(); // variable que usa para el metodo de buscar public DefaultTableModel getModel() { return model; } public void setModel(DefaultTableModel model) { this.model = model; } //Metodos para buscar por rango de fecha private Connection conexion; private Statement st; private ResultSet rs; PreparedStatement ps; /** * se hace la conexion a la Base de datos y se hace la consulta hacia la * tabla de ventas que tiene una union con la tabla de * detalle ventas y que a su ves esta conectada con la tabla de productos */ public void Conectar() { try { conexion =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia","root",""); //conexion = DriverManager.getConnection("jdbc:mysql://raspberry-tic41.zapto.org:3306/StockCia", "tic41", "tic41"); st = conexion.createStatement(); rs = st.executeQuery("SELECT ventas.id_ventas, fecha_venta, RFC_cliente, RFC_empleado, no_sucursal, codigo_descuento, puntos_ganados, detalle_ventas.Id_detalle_venta, codigo_producto, cantidad, precio_venta, total_producto FROM ventas INNER JOIN detalle_ventas ON ventas.id_ventas = detalle_ventas.id_ventas;"); rs.first(); } catch (SQLException err) { JOptionPane.showMessageDialog(null, "Error " + err.getMessage()); } } public void mostrar() { ResultSet rs = Database.getTabla("SELECT ventas.id_ventas, fecha_venta, RFC_cliente, RFC_empleado, no_sucursal, codigo_descuento, puntos_ganados, detalle_ventas.Id_detalle_venta, codigo_producto, cantidad, precio_venta, total_producto FROM ventas INNER JOIN detalle_ventas ON ventas.id_ventas = detalle_ventas.id_ventas;"); modelo_detalle_ventas.setColumnIdentifiers(new Object[]{"Id venta", "Fecha","RFC cliente","RFC empleado", "No sucursal", "Codigo descuento", "Puntos ganados", "Id detalle venta","Codigo producto", "Cantidad", "Precio venta", "Total"}); try { while (rs.next()) { // añade los resultado a al modelo de tabla modelo_detalle_ventas.addRow(new Object[]{ rs.getString("ventas.id_ventas"), rs.getString("ventas.fecha_venta"), rs.getString("ventas.RFC_cliente"), rs.getString("ventas.RFC_empleado"), rs.getString("ventas.no_sucursal"), rs.getString("ventas.codigo_descuento"), rs.getString("ventas.puntos_ganados"), rs.getString("detalle_ventas.Id_detalle_venta"), rs.getString("detalle_ventas.codigo_producto"), rs.getString("detalle_ventas.cantidad"), rs.getString("detalle_ventas.precio_venta"), rs.getString("detalle_ventas.total_producto")}); } } catch (Exception e) { System.out.println(e); } } public void mostrarProducto(){ try{ rs = st.executeQuery("select detalle_ventas.codigo_producto,nom_producto, count(detalle_ventas.codigo_producto) as cantidad from detalle_ventas inner join productos on detalle_ventas.codigo_producto = productos.codigo_producto group by codigo_producto order by cantidad desc");//consulta a descuentos rs.first(); nombre_producto = rs.getString("nom_producto"); }catch (Exception e) { System.out.println(e); } } public void mostrarProductoMenor(){ try{ rs = st.executeQuery("select detalle_ventas.codigo_producto,nom_producto, count(detalle_ventas.codigo_producto) as cantidad from detalle_ventas inner join productos on detalle_ventas.codigo_producto = productos.codigo_producto group by codigo_producto order by cantidad desc");//consulta a descuentos rs.last(); producto_menor = rs.getString("nom_producto"); }catch (Exception e) { System.out.println(e); } } public void mostrarVendedor(){ try{ rs = st.executeQuery("select RFC_empleado,nombre_empl_vent,ap_pat_vent,ap_mat_vent, count(RFC_empleado) as cantidad from ventas inner join empleados_ventas on ventas.RFC_empleado = empleados_ventas.RFC_empl_vent group by RFC_empleado order by cantidad desc");//consulta a descuentos rs.first(); nombre_empleado = rs.getString("nombre_empl_vent"); apellido_paterno = rs.getString("ap_pat_vent"); apellido_materno = rs.getString("ap_mat_vent"); }catch (Exception e) { System.out.println(e); } } }<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewMenuAdmin extends javax.swing.JFrame { /** * Creates new form ViewMenu */ public ViewMenuAdmin() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jl_CiaLogo = new javax.swing.JLabel(); jmi_detalle_compra1 = new javax.swing.JMenuBar(); jm_catalogos = new javax.swing.JMenu(); jmi_proveedores = new javax.swing.JMenuItem(); jmi_clientes = new javax.swing.JMenuItem(); jmi_empleados_compras = new javax.swing.JMenuItem(); jmi_empleados_ventas = new javax.swing.JMenuItem(); jmi_sucursales = new javax.swing.JMenuItem(); jmi_productos = new javax.swing.JMenuItem(); jm_detalles = new javax.swing.JMenu(); jmi_detallecompra = new javax.swing.JMenuItem(); jmi_detalleventa = new javax.swing.JMenuItem(); jm_nueva_sucursal = new javax.swing.JMenu(); jmi_agregar_Sucursal = new javax.swing.JMenuItem(); jmi_descuentos = new javax.swing.JMenuItem(); jmi_promociones = new javax.swing.JMenuItem(); jm_opciones = new javax.swing.JMenu(); jmi_respaldoBD = new javax.swing.JMenuItem(); jmi_salir = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(0, 153, 153)); jl_CiaLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/CIA-Developers.png"))); // NOI18N jmi_detalle_compra1.setBackground(new java.awt.Color(102, 102, 102)); jmi_detalle_compra1.setPreferredSize(new java.awt.Dimension(88, 35)); jm_catalogos.setBackground(new java.awt.Color(255, 255, 102)); jm_catalogos.setForeground(new java.awt.Color(255, 255, 255)); jm_catalogos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/catalogos.png"))); // NOI18N jm_catalogos.setText("Catalogos"); jmi_proveedores.setBackground(new java.awt.Color(255, 255, 255)); jmi_proveedores.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Proveedores.png"))); // NOI18N jmi_proveedores.setText("Proveedores"); jm_catalogos.add(jmi_proveedores); jmi_clientes.setBackground(new java.awt.Color(255, 255, 255)); jmi_clientes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/clientes.png"))); // NOI18N jmi_clientes.setText("Clientes"); jm_catalogos.add(jmi_clientes); jmi_empleados_compras.setBackground(new java.awt.Color(255, 255, 255)); jmi_empleados_compras.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Empleados.png"))); // NOI18N jmi_empleados_compras.setText("Empleados compras"); jm_catalogos.add(jmi_empleados_compras); jmi_empleados_ventas.setBackground(new java.awt.Color(255, 255, 255)); jmi_empleados_ventas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Empleados.png"))); // NOI18N jmi_empleados_ventas.setText("Empleados ventas"); jm_catalogos.add(jmi_empleados_ventas); jmi_sucursales.setBackground(new java.awt.Color(255, 255, 255)); jmi_sucursales.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/sucursales.png"))); // NOI18N jmi_sucursales.setText("sucursales"); jm_catalogos.add(jmi_sucursales); jmi_productos.setBackground(new java.awt.Color(255, 255, 255)); jmi_productos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/productos.png"))); // NOI18N jmi_productos.setText("Productos"); jm_catalogos.add(jmi_productos); jmi_detalle_compra1.add(jm_catalogos); jm_detalles.setBackground(new java.awt.Color(0, 153, 204)); jm_detalles.setForeground(new java.awt.Color(255, 255, 255)); jm_detalles.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/aceptar.png"))); // NOI18N jm_detalles.setText("Detalles "); jmi_detallecompra.setBackground(new java.awt.Color(255, 255, 255)); jmi_detallecompra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/compras.png"))); // NOI18N jmi_detallecompra.setText("Detalle Compra"); jm_detalles.add(jmi_detallecompra); jmi_detalleventa.setBackground(new java.awt.Color(255, 255, 255)); jmi_detalleventa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Ventas.png"))); // NOI18N jmi_detalleventa.setText("Detalle Venta"); jmi_detalleventa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jmi_detalleventaActionPerformed(evt); } }); jm_detalles.add(jmi_detalleventa); jmi_detalle_compra1.add(jm_detalles); jm_nueva_sucursal.setForeground(new java.awt.Color(255, 255, 255)); jm_nueva_sucursal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/accionesAdmin.png"))); // NOI18N jm_nueva_sucursal.setText("Acciones"); jmi_agregar_Sucursal.setBackground(new java.awt.Color(255, 255, 255)); jmi_agregar_Sucursal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/agregar.png"))); // NOI18N jmi_agregar_Sucursal.setText("Agregar Nueva Sucursal "); jm_nueva_sucursal.add(jmi_agregar_Sucursal); jmi_descuentos.setBackground(new java.awt.Color(255, 255, 255)); jmi_descuentos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/descuentos.png"))); // NOI18N jmi_descuentos.setText("Descuentos"); jm_nueva_sucursal.add(jmi_descuentos); jmi_promociones.setBackground(new java.awt.Color(255, 255, 255)); jmi_promociones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/promociones.png"))); // NOI18N jmi_promociones.setText("Promociones"); jm_nueva_sucursal.add(jmi_promociones); jmi_detalle_compra1.add(jm_nueva_sucursal); jm_opciones.setForeground(new java.awt.Color(255, 255, 255)); jm_opciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/opciones.png"))); // NOI18N jm_opciones.setText("Opciones"); jmi_respaldoBD.setBackground(new java.awt.Color(255, 255, 255)); jmi_respaldoBD.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/RespaldoBD.png"))); // NOI18N jmi_respaldoBD.setText("RespaldoBD"); jm_opciones.add(jmi_respaldoBD); jmi_salir.setBackground(new java.awt.Color(255, 255, 255)); jmi_salir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Menu/Salir.png"))); // NOI18N jmi_salir.setText("Salir"); jm_opciones.add(jmi_salir); jmi_detalle_compra1.add(jm_opciones); setJMenuBar(jmi_detalle_compra1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(881, Short.MAX_VALUE) .addComponent(jl_CiaLogo) .addGap(27, 27, 27)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(423, Short.MAX_VALUE) .addComponent(jl_CiaLogo) .addGap(34, 34, 34)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jmi_detalleventaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_detalleventaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jmi_detalleventaActionPerformed private void jmi_descuentosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_descuentosActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jmi_descuentosActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ViewMenuAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ViewMenuAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ViewMenuAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ViewMenuAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ViewMenuAdmin().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jl_CiaLogo; public javax.swing.JMenu jm_catalogos; public javax.swing.JMenu jm_detalles; public javax.swing.JMenu jm_nueva_sucursal; public javax.swing.JMenu jm_opciones; public javax.swing.JMenuItem jmi_agregar_Sucursal; public javax.swing.JMenuItem jmi_clientes; public javax.swing.JMenuItem jmi_descuentos; public javax.swing.JMenuBar jmi_detalle_compra1; public javax.swing.JMenuItem jmi_detallecompra; public javax.swing.JMenuItem jmi_detalleventa; public javax.swing.JMenuItem jmi_empleados_compras; public javax.swing.JMenuItem jmi_empleados_ventas; public javax.swing.JMenuItem jmi_productos; public javax.swing.JMenuItem jmi_promociones; public javax.swing.JMenuItem jmi_proveedores; public javax.swing.JMenuItem jmi_respaldoBD; public javax.swing.JMenuItem jmi_salir; public javax.swing.JMenuItem jmi_sucursales; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewVENTAS extends javax.swing.JPanel { /** * Creates new form ViewVENTAS */ public ViewVENTAS() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jp_titulo2 = new javax.swing.JPanel(); jl_titulo2 = new javax.swing.JLabel(); fecha = new rojeru_san.RSLabelFecha(); hora = new rojeru_san.RSLabelHora(); jp_datos = new javax.swing.JPanel(); jl_empleado = new javax.swing.JLabel(); jl_numero_compras = new javax.swing.JLabel(); jl_cantidad = new javax.swing.JLabel(); jtf_cantidad = new javax.swing.JTextField(); jl_no_sucursal = new javax.swing.JLabel(); jl_precio_compra = new javax.swing.JLabel(); jtf_precio = new javax.swing.JTextField(); jp_cliente = new javax.swing.JPanel(); jl_numero_proveedor = new javax.swing.JLabel(); jcb_rfc_cliente = new javax.swing.JComboBox<>(); jl_nombre_proveedor = new javax.swing.JLabel(); jtf_nombre_cliente = new javax.swing.JTextField(); jl_telefono_proveedor = new javax.swing.JLabel(); jtf_puntos_acumulados = new javax.swing.JTextField(); jtf_numero_venta = new javax.swing.JTextField(); jl_total = new javax.swing.JLabel(); jtf_total = new javax.swing.JTextField(); jp_productos = new javax.swing.JPanel(); jl_codigo_producto = new javax.swing.JLabel(); jl_nombre_producto = new javax.swing.JLabel(); jtf_nombre_producto = new javax.swing.JTextField(); jl_tipo_producto = new javax.swing.JLabel(); jtf_tipo_producto = new javax.swing.JTextField(); jl_marca_producto = new javax.swing.JLabel(); jtf_marca_producto = new javax.swing.JTextField(); jcb_codigo_producto = new javax.swing.JComboBox<>(); jcb_numero_sucursal = new javax.swing.JComboBox<>(); jcb_rfc = new javax.swing.JComboBox<>(); jl_nombre_empleado = new javax.swing.JLabel(); jtf_nombre_empleado = new javax.swing.JTextField(); jl_status = new javax.swing.JLabel(); jl_status_producto = new javax.swing.JLabel(); jb_agregar = new javax.swing.JButton(); jb_nuevo = new javax.swing.JButton(); jb_eliminar = new javax.swing.JButton(); jb_modificar = new javax.swing.JButton(); jl_agregar = new javax.swing.JLabel(); jl_modificar = new javax.swing.JLabel(); jl_nuevo = new javax.swing.JLabel(); jl_eliminar = new javax.swing.JLabel(); jp_table = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jt_vista = new javax.swing.JTable(); jtf_subtotal = new javax.swing.JTextField(); jl_subtotal = new javax.swing.JLabel(); jl_iva = new javax.swing.JLabel(); jtf_iva = new javax.swing.JTextField(); jl_importe = new javax.swing.JLabel(); jtf_importe = new javax.swing.JTextField(); jb_realizar_venta = new javax.swing.JButton(); jp_pago = new javax.swing.JPanel(); jl_efectivo = new javax.swing.JLabel(); jtf_efectivo = new javax.swing.JTextField(); jl_cambio = new javax.swing.JLabel(); jtf_cambio = new javax.swing.JTextField(); jl_aplicar_descuentos = new javax.swing.JLabel(); jb_aplicar_descuento = new javax.swing.JButton(); jl_codigo_descuento = new javax.swing.JLabel(); jcb_codigo_descuento = new javax.swing.JComboBox<>(); jtf_puntos_requeridos = new javax.swing.JTextField(); jl_puntos_requeridos = new javax.swing.JLabel(); jl_porcentaje = new javax.swing.JLabel(); jtf_porcentaje = new javax.swing.JTextField(); jl_descuento = new javax.swing.JLabel(); jtf_descuento = new javax.swing.JTextField(); jl_puntos_ganados = new javax.swing.JLabel(); jtf_puntos_ganados = new javax.swing.JTextField(); setBackground(new java.awt.Color(255, 255, 255)); setMaximumSize(new java.awt.Dimension(1150, 692)); setMinimumSize(new java.awt.Dimension(1150, 692)); jp_titulo2.setBackground(new java.awt.Color(153, 204, 255)); jp_titulo2.setMaximumSize(new java.awt.Dimension(1150, 692)); jp_titulo2.setMinimumSize(new java.awt.Dimension(1150, 692)); jp_titulo2.setPreferredSize(new java.awt.Dimension(1150, 692)); jl_titulo2.setFont(new java.awt.Font("Segoe UI", 0, 45)); // NOI18N jl_titulo2.setForeground(new java.awt.Color(102, 102, 102)); jl_titulo2.setText("Ventas"); fecha.setForeground(new java.awt.Color(0, 0, 153)); fecha.setFont(new java.awt.Font("Segoe UI", 1, 20)); // NOI18N fecha.setFormato("dd-MM-yyyy"); hora.setForeground(new java.awt.Color(0, 0, 153)); hora.setFont(new java.awt.Font("Segoe UI", 1, 20)); // NOI18N javax.swing.GroupLayout jp_titulo2Layout = new javax.swing.GroupLayout(jp_titulo2); jp_titulo2.setLayout(jp_titulo2Layout); jp_titulo2Layout.setHorizontalGroup( jp_titulo2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_titulo2Layout.createSequentialGroup() .addGap(46, 46, 46) .addComponent(jl_titulo2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(hora, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(24, 24, 24)) ); jp_titulo2Layout.setVerticalGroup( jp_titulo2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_titulo2Layout.createSequentialGroup() .addContainerGap() .addGroup(jp_titulo2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(hora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_titulo2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_datos.setBackground(new java.awt.Color(255, 255, 255)); jp_datos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 14), new java.awt.Color(0, 153, 255))); // NOI18N jl_empleado.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_empleado.setText("Empleado:"); jl_numero_compras.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_numero_compras.setText("No. venta:"); jl_cantidad.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_cantidad.setText("Cantiad venta:"); jtf_cantidad.setBackground(new java.awt.Color(153, 153, 153)); jtf_cantidad.setText("0"); jl_no_sucursal.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_no_sucursal.setText("No_ sucursal:"); jl_precio_compra.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_precio_compra.setText("Precio venta $:"); jtf_precio.setEditable(false); jtf_precio.setBackground(new java.awt.Color(153, 153, 153)); jtf_precio.setText("0.0"); jp_cliente.setBackground(new java.awt.Color(255, 255, 255)); jp_cliente.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cliente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 12), new java.awt.Color(51, 153, 255))); // NOI18N jp_cliente.setForeground(new java.awt.Color(51, 153, 255)); jl_numero_proveedor.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_numero_proveedor.setText("RFC:"); jcb_rfc_cliente.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5" })); jl_nombre_proveedor.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nombre_proveedor.setText("Nombre :"); jtf_nombre_cliente.setEditable(false); jl_telefono_proveedor.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_telefono_proveedor.setText("Puntos acumulados"); jtf_puntos_acumulados.setEditable(false); javax.swing.GroupLayout jp_clienteLayout = new javax.swing.GroupLayout(jp_cliente); jp_cliente.setLayout(jp_clienteLayout); jp_clienteLayout.setHorizontalGroup( jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_clienteLayout.createSequentialGroup() .addGroup(jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_clienteLayout.createSequentialGroup() .addComponent(jl_numero_proveedor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_rfc_cliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jp_clienteLayout.createSequentialGroup() .addComponent(jl_nombre_proveedor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_nombre_cliente))) .addGap(10, 10, 10)) .addGroup(jp_clienteLayout.createSequentialGroup() .addComponent(jl_telefono_proveedor) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_puntos_acumulados, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE) .addContainerGap()) ); jp_clienteLayout.setVerticalGroup( jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_clienteLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcb_rfc_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_numero_proveedor)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nombre_proveedor) .addComponent(jtf_nombre_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_clienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_telefono_proveedor) .addComponent(jtf_puntos_acumulados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jtf_numero_venta.setEditable(false); jl_total.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_total.setText("Total $:"); jtf_total.setEditable(false); jtf_total.setBackground(new java.awt.Color(0, 0, 0)); jtf_total.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N jtf_total.setForeground(new java.awt.Color(51, 153, 255)); jtf_total.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_total.setText("0.00"); jtf_total.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); jp_productos.setBackground(new java.awt.Color(255, 255, 255)); jp_productos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Producto", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 12), new java.awt.Color(51, 153, 255))); // NOI18N jp_productos.setForeground(new java.awt.Color(51, 153, 255)); jl_codigo_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_codigo_producto.setText("Codigo producto:"); jl_nombre_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nombre_producto.setText("Nombre producto:"); jtf_nombre_producto.setEditable(false); jl_tipo_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_tipo_producto.setText("Tipo producto:"); jtf_tipo_producto.setEditable(false); jl_marca_producto.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_marca_producto.setText(" Marca producto:"); jtf_marca_producto.setEditable(false); jcb_codigo_producto.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5" })); javax.swing.GroupLayout jp_productosLayout = new javax.swing.GroupLayout(jp_productos); jp_productos.setLayout(jp_productosLayout); jp_productosLayout.setHorizontalGroup( jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_productosLayout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jl_marca_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_marca_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jp_productosLayout.createSequentialGroup() .addContainerGap() .addComponent(jl_codigo_producto) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_codigo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(55, Short.MAX_VALUE)) .addGroup(jp_productosLayout.createSequentialGroup() .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_nombre_producto) .addComponent(jl_tipo_producto)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_nombre_producto) .addComponent(jtf_tipo_producto)) .addContainerGap()) ); jp_productosLayout.setVerticalGroup( jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_productosLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_codigo_producto) .addComponent(jcb_codigo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nombre_producto) .addComponent(jtf_nombre_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_tipo_producto) .addComponent(jtf_tipo_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_productosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_marca_producto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_marca_producto)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jcb_numero_sucursal.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "1", "2", "3", "4", "5" })); jcb_rfc.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jl_nombre_empleado.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_nombre_empleado.setText("Nombre:"); jtf_nombre_empleado.setEditable(false); jl_status.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_status.setText("Status:"); jl_status_producto.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_status_producto.setForeground(new java.awt.Color(204, 0, 0)); jl_status_producto.setText("Normal"); javax.swing.GroupLayout jp_datosLayout = new javax.swing.GroupLayout(jp_datos); jp_datos.setLayout(jp_datosLayout); jp_datosLayout.setHorizontalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_empleado) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_rfc, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jl_numero_compras) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_numero_venta, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jl_no_sucursal, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_numero_sucursal, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jl_status) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jl_status_producto)) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jp_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_nombre_empleado) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_nombre_empleado))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jp_productos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addComponent(jl_precio_compra) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_precio, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addComponent(jl_total) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_total, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addComponent(jl_cantidad) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(35, Short.MAX_VALUE)) ); jp_datosLayout.setVerticalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_status) .addComponent(jl_status_producto)) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_empleado) .addComponent(jl_numero_compras) .addComponent(jtf_numero_venta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_no_sucursal) .addComponent(jcb_numero_sucursal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcb_rfc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_nombre_empleado) .addComponent(jtf_nombre_empleado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jp_cliente, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58)) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_productos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_cantidad) .addComponent(jtf_cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_precio_compra) .addComponent(jtf_precio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_total) .addComponent(jtf_total, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jb_agregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/BotonAgregar.png"))); // NOI18N jb_nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/nuevo.png"))); // NOI18N jb_eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/eliminar.png"))); // NOI18N jb_modificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/ModProd.jpeg"))); // NOI18N jl_agregar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_agregar.setText("Agregar"); jl_modificar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_modificar.setText("Modificar"); jl_nuevo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_nuevo.setText("Nuevo"); jl_eliminar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_eliminar.setForeground(new java.awt.Color(51, 51, 51)); jl_eliminar.setText("Eliminar"); jp_table.setBackground(new java.awt.Color(255, 255, 51)); jt_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "Id Compra", "Codigo Producto", "Nombre Producto", "Precio", "Cantidad", "Total" } )); jScrollPane1.setViewportView(jt_vista); javax.swing.GroupLayout jp_tableLayout = new javax.swing.GroupLayout(jp_table); jp_table.setLayout(jp_tableLayout); jp_tableLayout.setHorizontalGroup( jp_tableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_tableLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); jp_tableLayout.setVerticalGroup( jp_tableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_tableLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE) .addContainerGap()) ); jtf_subtotal.setEditable(false); jtf_subtotal.setBackground(new java.awt.Color(153, 153, 153)); jtf_subtotal.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_subtotal.setText("0.0"); jl_subtotal.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_subtotal.setText("Subtotal $:"); jl_iva.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_iva.setText("IVA $:"); jtf_iva.setEditable(false); jtf_iva.setBackground(new java.awt.Color(153, 153, 153)); jtf_iva.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_iva.setText("0.0"); jl_importe.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N jl_importe.setForeground(new java.awt.Color(0, 102, 204)); jl_importe.setText("IMPORTE $:"); jtf_importe.setEditable(false); jtf_importe.setBackground(new java.awt.Color(0, 0, 0)); jtf_importe.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N jtf_importe.setForeground(new java.awt.Color(255, 0, 0)); jtf_importe.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_importe.setText("0.00"); jtf_importe.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); jb_realizar_venta.setBackground(new java.awt.Color(51, 51, 51)); jb_realizar_venta.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jb_realizar_venta.setForeground(new java.awt.Color(255, 255, 255)); jb_realizar_venta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Compra_venta.png"))); // NOI18N jb_realizar_venta.setText("Realizar Venta..."); jp_pago.setBackground(new java.awt.Color(255, 255, 255)); jp_pago.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "pago", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 12), new java.awt.Color(51, 153, 255))); // NOI18N jp_pago.setForeground(new java.awt.Color(51, 153, 255)); jl_efectivo.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_efectivo.setText("Efectivo:"); jtf_efectivo.setBackground(new java.awt.Color(153, 153, 153)); jtf_efectivo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jtf_efectivo.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_efectivo.setText("0.0"); jl_cambio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_cambio.setText("Cambio:"); jtf_cambio.setEditable(false); jtf_cambio.setBackground(new java.awt.Color(153, 153, 153)); jtf_cambio.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jtf_cambio.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_cambio.setText("0.0"); jl_aplicar_descuentos.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_aplicar_descuentos.setForeground(new java.awt.Color(153, 0, 153)); jl_aplicar_descuentos.setText("Aplicar descuento."); jb_aplicar_descuento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/descuento_ventas.png"))); // NOI18N jl_codigo_descuento.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_codigo_descuento.setText("codigo descuento:"); jcb_codigo_descuento.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jtf_puntos_requeridos.setEditable(false); jtf_puntos_requeridos.setBackground(new java.awt.Color(204, 102, 255)); jtf_puntos_requeridos.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_puntos_requeridos.setText("0.0"); jl_puntos_requeridos.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_puntos_requeridos.setText("puntos requeridos:"); jl_porcentaje.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_porcentaje.setText("porcentaje:"); jtf_porcentaje.setEditable(false); jtf_porcentaje.setBackground(new java.awt.Color(204, 102, 255)); jtf_porcentaje.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_porcentaje.setText("0.0"); jl_descuento.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_descuento.setText("descuento $:"); jtf_descuento.setEditable(false); jtf_descuento.setBackground(new java.awt.Color(204, 102, 255)); jtf_descuento.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_descuento.setText("0.0"); javax.swing.GroupLayout jp_pagoLayout = new javax.swing.GroupLayout(jp_pago); jp_pago.setLayout(jp_pagoLayout); jp_pagoLayout.setHorizontalGroup( jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createSequentialGroup() .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createSequentialGroup() .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_puntos_requeridos) .addComponent(jl_porcentaje)) .addComponent(jb_aplicar_descuento, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtf_porcentaje, javax.swing.GroupLayout.DEFAULT_SIZE, 146, Short.MAX_VALUE) .addComponent(jtf_puntos_requeridos)) .addComponent(jl_aplicar_descuentos))) .addGroup(jp_pagoLayout.createSequentialGroup() .addComponent(jl_codigo_descuento) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcb_codigo_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jp_pagoLayout.createSequentialGroup() .addComponent(jl_efectivo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_efectivo)) .addGroup(jp_pagoLayout.createSequentialGroup() .addComponent(jl_cambio) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_cambio, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_pagoLayout.createSequentialGroup() .addComponent(jl_descuento) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); jp_pagoLayout.setVerticalGroup( jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_pagoLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jl_aplicar_descuentos)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_pagoLayout.createSequentialGroup() .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_codigo_descuento) .addComponent(jcb_codigo_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_descuento)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_puntos_requeridos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_puntos_requeridos)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_porcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_porcentaje)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jp_pagoLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_efectivo) .addComponent(jtf_efectivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21))) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_pagoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_cambio) .addComponent(jtf_cambio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jb_aplicar_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jl_puntos_ganados.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_puntos_ganados.setForeground(new java.awt.Color(0, 0, 153)); jl_puntos_ganados.setText("puntos ganados:"); jtf_puntos_ganados.setBackground(new java.awt.Color(153, 204, 255)); jtf_puntos_ganados.setHorizontalAlignment(javax.swing.JTextField.CENTER); jtf_puntos_ganados.setText("0"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_titulo2, javax.swing.GroupLayout.DEFAULT_SIZE, 1195, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_pago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jl_subtotal) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_subtotal, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jl_iva) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_iva, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jb_realizar_venta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtf_importe, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(46, 46, 46) .addComponent(jl_importe))) .addComponent(jl_puntos_ganados, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jtf_puntos_ganados, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(90, 90, 90)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_table, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_agregar) .addComponent(jb_agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_nuevo)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_modificar) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_eliminar) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 16, Short.MAX_VALUE))) .addContainerGap()))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_titulo2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jb_agregar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jl_agregar)) .addGroup(layout.createSequentialGroup() .addComponent(jb_modificar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jl_modificar))) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jb_nuevo) .addGap(7, 7, 7) .addComponent(jl_nuevo)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(67, 67, 67) .addComponent(jl_eliminar))))) .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jp_table, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_pago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jl_importe) .addGap(8, 8, 8) .addComponent(jtf_importe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jl_puntos_ganados) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_puntos_ganados, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_subtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_subtotal)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_iva) .addComponent(jtf_iva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(27, 27, 27) .addComponent(jb_realizar_venta, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(55, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private rojeru_san.RSLabelFecha fecha; private rojeru_san.RSLabelHora hora; private javax.swing.JScrollPane jScrollPane1; public javax.swing.JButton jb_agregar; public javax.swing.JButton jb_aplicar_descuento; public javax.swing.JButton jb_eliminar; public javax.swing.JButton jb_modificar; public javax.swing.JButton jb_nuevo; public javax.swing.JButton jb_realizar_venta; public javax.swing.JComboBox<String> jcb_codigo_descuento; public javax.swing.JComboBox<String> jcb_codigo_producto; public javax.swing.JComboBox<String> jcb_numero_sucursal; public javax.swing.JComboBox<String> jcb_rfc; public javax.swing.JComboBox<String> jcb_rfc_cliente; public javax.swing.JLabel jl_agregar; public javax.swing.JLabel jl_aplicar_descuentos; private javax.swing.JLabel jl_cambio; public javax.swing.JLabel jl_cantidad; public javax.swing.JLabel jl_codigo_descuento; public javax.swing.JLabel jl_codigo_producto; public javax.swing.JLabel jl_descuento; private javax.swing.JLabel jl_efectivo; public javax.swing.JLabel jl_eliminar; public javax.swing.JLabel jl_empleado; public javax.swing.JLabel jl_importe; public javax.swing.JLabel jl_iva; public javax.swing.JLabel jl_marca_producto; public javax.swing.JLabel jl_modificar; public javax.swing.JLabel jl_no_sucursal; public javax.swing.JLabel jl_nombre_empleado; public javax.swing.JLabel jl_nombre_producto; public javax.swing.JLabel jl_nombre_proveedor; public javax.swing.JLabel jl_nuevo; public javax.swing.JLabel jl_numero_compras; public javax.swing.JLabel jl_numero_proveedor; public javax.swing.JLabel jl_porcentaje; public javax.swing.JLabel jl_precio_compra; public javax.swing.JLabel jl_puntos_ganados; public javax.swing.JLabel jl_puntos_requeridos; public javax.swing.JLabel jl_status; public javax.swing.JLabel jl_status_producto; public javax.swing.JLabel jl_subtotal; public javax.swing.JLabel jl_telefono_proveedor; public javax.swing.JLabel jl_tipo_producto; public javax.swing.JLabel jl_titulo2; public javax.swing.JLabel jl_total; public javax.swing.JPanel jp_cliente; public javax.swing.JPanel jp_datos; public javax.swing.JPanel jp_pago; public javax.swing.JPanel jp_productos; public javax.swing.JPanel jp_table; private javax.swing.JPanel jp_titulo2; public javax.swing.JTable jt_vista; public javax.swing.JTextField jtf_cambio; public javax.swing.JTextField jtf_cantidad; public javax.swing.JTextField jtf_descuento; public javax.swing.JTextField jtf_efectivo; public javax.swing.JTextField jtf_importe; public javax.swing.JTextField jtf_iva; public javax.swing.JTextField jtf_marca_producto; public javax.swing.JTextField jtf_nombre_cliente; public javax.swing.JTextField jtf_nombre_empleado; public javax.swing.JTextField jtf_nombre_producto; public javax.swing.JTextField jtf_numero_venta; public javax.swing.JTextField jtf_porcentaje; public javax.swing.JTextField jtf_precio; public javax.swing.JTextField jtf_puntos_acumulados; public javax.swing.JTextField jtf_puntos_ganados; public javax.swing.JTextField jtf_puntos_requeridos; public javax.swing.JTextField jtf_subtotal; public javax.swing.JTextField jtf_tipo_producto; public javax.swing.JTextField jtf_total; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; import models.ModelProveedores; import views.ViewProveedores; /** * * @author Octaviano */ public class ControllerProveedores { public ModelProveedores modelProveedores; public ViewProveedores viewProveedores; ActionListener list = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewProveedores.jb_nuevo) { nuevo_proveedores(); } else if (e.getSource() == viewProveedores.jb_modificar) { modificar_proveedores(); } else if (e.getSource() == viewProveedores.jb_guardar) { Guardar(); } } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewProveedores.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }; /** * Busar solo con un compo, no es necesario el metodo de filtro toda la * accion de buscar esta dentro del evento keyListener */ KeyListener key = new KeyListener() { @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewProveedores.jtf_buscar) { modelProveedores.setTrsFiltro(new TableRowSorter(viewProveedores.jt_vista.getModel())); viewProveedores.jt_vista.setRowSorter(modelProveedores.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { modelProveedores.setCadena(viewProveedores.jtf_buscar.getText()); viewProveedores.jtf_buscar.setText(modelProveedores.getCadena()); modelProveedores.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewProveedores.jtf_buscar.getText(), modelProveedores.getColumnaABuscar())); } }; public ControllerProveedores(ModelProveedores modelProveedores, ViewProveedores viewProveedores) { this.modelProveedores = modelProveedores; this.viewProveedores = viewProveedores; this.viewProveedores.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la caja e texto buscar this.viewProveedores.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener viewProveedores.jb_guardar.setEnabled(false); //El boton guardar aparecera inhabilitado viewProveedores.jb_eliminar.setEnabled(false); //El boton guardar aparecera inhabilitado cajas_deshabilitadas(); setActionListener(); ConexionBD(); } /** * Método para agregar el actionListener a cada boton */ private void setActionListener() { viewProveedores.jb_nuevo.addActionListener(list); viewProveedores.jb_modificar.addActionListener(list); viewProveedores.jb_guardar.addActionListener(list); } public void ConexionBD() { modelProveedores.Conectar(); modelProveedores.mostrar(); viewProveedores.jt_vista.setModel(modelProveedores.getModelo_Proveedores()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked() { viewProveedores.jb_guardar.setEnabled(false); viewProveedores.jb_modificar.setEnabled(true);//El boton modificar aparecera habilitado viewProveedores.jb_nuevo.setEnabled(true);//El boton nuevo aparecera habilitado cajas_deshabilitadas(); // cuando se haga clic en la tabla, las cajas se volveran a deshabilitar modelProveedores.setRec(viewProveedores.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewProveedores.jtf_id.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 0).toString()); viewProveedores.jtf_nombre.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 1).toString()); viewProveedores.jtf_ap_pat.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 2).toString()); viewProveedores.jtf_apt_mat.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 3).toString()); viewProveedores.jtf_telefono.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 4).toString()); viewProveedores.jtf_municipio.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 5).toString()); viewProveedores.jtf_colonia.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 6).toString()); viewProveedores.jtf_numero.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 7).toString()); viewProveedores.jtf_provincia.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 8).toString()); viewProveedores.jtf_correo.setText(viewProveedores.jt_vista.getValueAt(modelProveedores.getRec(), 9).toString()); } private void cajas_deshabilitadas() { viewProveedores.jtf_id.setEditable(false); viewProveedores.jtf_nombre.setEditable(false); viewProveedores.jtf_ap_pat.setEditable(false); viewProveedores.jtf_apt_mat.setEditable(false); viewProveedores.jtf_telefono.setEditable(false); viewProveedores.jtf_municipio.setEditable(false); viewProveedores.jtf_colonia.setEditable(false); viewProveedores.jtf_numero.setEditable(false); viewProveedores.jtf_provincia.setEditable(false); viewProveedores.jtf_correo.setEditable(false); } private void cajas_habilitadas() { viewProveedores.jtf_id.setEditable(true); viewProveedores.jtf_nombre.setEditable(true); viewProveedores.jtf_ap_pat.setEditable(true); viewProveedores.jtf_apt_mat.setEditable(true); viewProveedores.jtf_telefono.setEditable(true); viewProveedores.jtf_municipio.setEditable(true); viewProveedores.jtf_colonia.setEditable(true); viewProveedores.jtf_numero.setEditable(true); viewProveedores.jtf_provincia.setEditable(true); viewProveedores.jtf_correo.setEditable(true); } //***************** BOTONES Nuevo, Borrar, Guardar y Modificar************************** /** * Metodo que limpiara las cajas de texto para ingresar nuevo datos. */ public void nuevo_proveedores() { viewProveedores.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewProveedores.jb_modificar.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelProveedores.setVerificar(1);// le da el valor a verificar de cero para identificar un nuevo registroç viewProveedores.jtf_id.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_nombre.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_ap_pat.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_apt_mat.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_telefono.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_municipio.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_colonia.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_numero.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_provincia.setText(modelProveedores.getLimpiar()); viewProveedores.jtf_correo.setText(modelProveedores.getLimpiar()); cajas_habilitadas();//llamar al metodo de cajas habilitadas para proceder a escribir un nuevo registro } public void modificar_proveedores() { viewProveedores.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewProveedores.jb_modificar.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelProveedores.setVerificar(2);// le da el valor a verificar de uno para identificar Modifiar registro viewProveedores.jtf_id.setEditable(false); // el codigo no se puede modificar viewProveedores.jtf_nombre.setEditable(true); viewProveedores.jtf_ap_pat.setEditable(true); viewProveedores.jtf_apt_mat.setEditable(true); viewProveedores.jtf_telefono.setEditable(true); viewProveedores.jtf_municipio.setEditable(true); viewProveedores.jtf_colonia.setEditable(true); viewProveedores.jtf_numero.setEditable(true); viewProveedores.jtf_provincia.setEditable(true); viewProveedores.jtf_correo.setEditable(true); } public void Guardar() { // si la variable verificar es igual a 0 se llama al metodo de guardar Nuevo if (modelProveedores.getVerificar() == 1) { // darle el valor a las variables modelProveedores.setId(viewProveedores.jtf_id.getText()); modelProveedores.setNombre(viewProveedores.jtf_nombre.getText()); modelProveedores.setAp_pat(viewProveedores.jtf_ap_pat.getText()); modelProveedores.setAp_mat(viewProveedores.jtf_apt_mat.getText()); modelProveedores.setTelefono(viewProveedores.jtf_telefono.getText()); modelProveedores.setCalle(viewProveedores.jtf_municipio.getText()); modelProveedores.setColonia(viewProveedores.jtf_colonia.getText()); modelProveedores.setNumero(viewProveedores.jtf_numero.getText()); modelProveedores.setProvincia(viewProveedores.jtf_provincia.getText()); modelProveedores.setCorreo(viewProveedores.jtf_correo.getText()); modelProveedores.Guardar_Nuevo(); // metodo de insertar nuevo registro } else { // darle el valor a las variables modelProveedores.setId(viewProveedores.jtf_id.getText()); modelProveedores.setNombre(viewProveedores.jtf_nombre.getText()); modelProveedores.setAp_pat(viewProveedores.jtf_ap_pat.getText()); modelProveedores.setAp_mat(viewProveedores.jtf_apt_mat.getText()); modelProveedores.setTelefono(viewProveedores.jtf_telefono.getText()); modelProveedores.setCalle(viewProveedores.jtf_municipio.getText()); modelProveedores.setColonia(viewProveedores.jtf_colonia.getText()); modelProveedores.setNumero(viewProveedores.jtf_numero.getText()); modelProveedores.setProvincia(viewProveedores.jtf_provincia.getText()); modelProveedores.setCorreo(viewProveedores.jtf_correo.getText()); modelProveedores.Guardar_Modificado();// metodo de Modificar el registro } //LIMPIAR TABLA for (int i = 0; i < viewProveedores.jt_vista.getRowCount(); i++) { modelProveedores.getModelo_Proveedores().removeRow(i); i -= 1; } //mostrar los nuevos datos modelProveedores.mostrar(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import models.ModelMenuEmpleadoCompras; import views.viewMenuEmpleadoCompras; /** * * @author Octaviano */ public class ControllerMenuEmpleadoCompras { private final ModelMenuEmpleadoCompras modelMenuEmpleadosCompras; private final viewMenuEmpleadoCompras viewMenuEmpleadosCompras; /** * Esta variable almacena los controladores de cada vista de catalogos * para poder utilizarlos dentro del mismo JFrame. */ private Object controllers[]; private ControllerClientesEmpleados controllerClientesEmpleados; private ControllerProductosEmpleados controllerProductosEmpleados; private ControllerProveedoresEmpleados controllerProveedoresEmpleados; private ControllerSucursalesEmpleados controllerSucursalesEmpleados; private ControllerCOMPRAS controllerCOMPRAS; /** * Controlador principal donde se un el modelo y controlador del MenuEmpleadosCompras * Recibe cada controlador de las vistas de los catalogos * dentro de este controlador se tiene el accesso a la programacion * en el controlador de cada JpanelCatalogo * @param modelMenuEmpleadosCompras * @param viewMenuWmpleadosCompras * @param controllers */ public ControllerMenuEmpleadoCompras(ModelMenuEmpleadoCompras modelMenuEmpleadosCompras, viewMenuEmpleadoCompras viewMenuWmpleadosCompras, Object[] controllers) { this.modelMenuEmpleadosCompras = modelMenuEmpleadosCompras; this.viewMenuEmpleadosCompras = viewMenuWmpleadosCompras; this.controllers = controllers; setControllers(); setActionListener(); initComponets(); } /** * Separa cada uno de los controlladores almacendados en controllers, de * esta forma se puede acceder a todas las variables y métodos publicos * de cada uno. */ public void setControllers() { controllerClientesEmpleados = (ControllerClientesEmpleados) controllers[0]; controllerProductosEmpleados = (ControllerProductosEmpleados) controllers[1]; controllerProveedoresEmpleados = (ControllerProveedoresEmpleados) controllers[2]; controllerSucursalesEmpleados = (ControllerSucursalesEmpleados) controllers[3]; controllerCOMPRAS = (ControllerCOMPRAS) controllers[4]; } /** * mustra la ventana principal del menuEmpleadosCompras */ private void initComponets(){ viewMenuEmpleadosCompras.setTitle("Menu Empleados Compras "); viewMenuEmpleadosCompras.setLocationRelativeTo(null); viewMenuEmpleadosCompras.setVisible(true); } /** * Asigna el actionListener a cada uno de los JMenuItems de la vista * ViewMenuAdmin. */ private void setActionListener() { viewMenuEmpleadosCompras.jmi_clientes.addActionListener(actionListener);; viewMenuEmpleadosCompras.jmi_productos.addActionListener(actionListener); viewMenuEmpleadosCompras.jmi_proveedores.addActionListener(actionListener); viewMenuEmpleadosCompras.jmi_sucursales.addActionListener(actionListener); viewMenuEmpleadosCompras.jmi_compras.addActionListener(actionListener); viewMenuEmpleadosCompras.jmi_salir.addActionListener(actionListener); } private final ActionListener actionListener = new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewMenuEmpleadosCompras.jmi_clientes) { jmi_clientes_actionPerformed(); }else if (e.getSource() == viewMenuEmpleadosCompras.jmi_productos) { jmi_productos_actionPerformed(); }else if (e.getSource() == viewMenuEmpleadosCompras.jmi_proveedores) { jmi_proveedores_actionPerformed(); }else if (e.getSource() == viewMenuEmpleadosCompras.jmi_sucursales) { jmi_sucursales_actionPerformed(); } else if (e.getSource() == viewMenuEmpleadosCompras.jmi_compras) { jmi_compras_actionPerformed(); }else if (e.getSource() == viewMenuEmpleadosCompras.jmi_salir) { modelMenuEmpleadosCompras.VentanaLogin(); viewMenuEmpleadosCompras.setVisible(false); } } }; /** * Muestra el JPanel ViewClientes dentro del JFrame ViewMenuEmpleadosCompras, (incluido todo * el funcionamiendo programado). */ private void jmi_clientes_actionPerformed(){ viewMenuEmpleadosCompras.setContentPane(controllerClientesEmpleados.viewClientesEmpleados); viewMenuEmpleadosCompras.revalidate(); viewMenuEmpleadosCompras.repaint(); } private void jmi_productos_actionPerformed(){ viewMenuEmpleadosCompras.setContentPane(controllerProductosEmpleados.viewProductosEmpleados); viewMenuEmpleadosCompras.revalidate(); viewMenuEmpleadosCompras.repaint(); } private void jmi_proveedores_actionPerformed(){ viewMenuEmpleadosCompras.setContentPane(controllerProveedoresEmpleados.viewProveedoresEmpleados); viewMenuEmpleadosCompras.revalidate(); viewMenuEmpleadosCompras.repaint(); } private void jmi_sucursales_actionPerformed(){ viewMenuEmpleadosCompras.setContentPane(controllerSucursalesEmpleados.viewSucursalesEmpleados); viewMenuEmpleadosCompras.revalidate(); viewMenuEmpleadosCompras.repaint(); } private void jmi_compras_actionPerformed(){ viewMenuEmpleadosCompras.setContentPane(controllerCOMPRAS.viewCOMPRAS); viewMenuEmpleadosCompras.revalidate(); viewMenuEmpleadosCompras.repaint(); } } <file_sep> Create database StockCia; use StockCia; CREATE TABLE productos ( codigo_producto VARCHAR(13) NOT NULL PRIMARY KEY, nom_producto VARCHAR(100) NOT NULL, tipo_producto VARCHAR(25) NOT NULL, marca VARCHAR(15) NOT NULL, precio_unitario_venta FLOAT NOT NULL, Unidad VARCHAR(15) NOT NULL, descripcion VARCHAR(100) NOT NULL, fecha_ingreso TIMESTAMP NOT NULL, existencia_total INT(25) NULL, status_prod VARCHAR ( 15 ) NOT NULL, image Varchar(100) null); insert into productos (codigo_producto,nom_producto,tipo_producto,marca,precio_unitario_venta,unidad,descripcion,fecha_ingreso,existencia_total,status_prod) values (1651,"lamina galvanizada calibre 16 de 4 x 8","construccion","Vimar",105.00,"pza","Lamina de acero con recubrimiento de zinc","2018-05-01",727,"en venta"), (1722,"Tuerca hexagonal de 5/8","ferreteria","Fastenere",20.00,"kg","Tuerca con una insercion de collar de nylon que resiste el giro.","2018-03-02",1308,"en venta"), (1658,"Tubo rectangular aluminio","construccion","Bosch",389.00,"pza","Tubo de 1m de lago y 12 mm de ancho ","2018-06-23",1098,"ya no se maneja"), (1321,"Clavos","ferreteria","Sithl",50.00,"kg","Clavos Estandar 3-2-1","2018-07-20",3330,"en venta"), (8170,"Motosierra" ,"jardin","Truper",500.00,"pza","Motosierra Electrica 18 pulgadas","2018-04-15",27,"en venta"); CREATE TABLE sucursal ( no_sucursal INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, calle VARCHAR(50) NOT NULL, colonia VARCHAR(50) NOT NULL, numero VARCHAR(5) NOT NULL, telefono VARCHAR(12) NOT NULL); insert into sucursal values (1,"<NAME>","Tulancingo",213,"7757532101"), (2,"<NAME>","Magisterio",333,"5575123047"), (3,"<NAME>","Jaltepec",152,"7757712362"), (4,"Cipres","<NAME>",122,"7751236547"), (5,"<NAME>","<NAME>",200,"5575896300"); CREATE TABLE sucursal_productos ( id_sucursal_productos INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, no_sucursal INT(15) NOT NULL, codigo_producto VARCHAR(10) NOT NULL, existencias INT(6) NOT NULL, limite_maximo INT(6) NOT NULL, limite_minimo INT(6) NOT NULL, FOREIGN KEY (no_sucursal) REFERENCES sucursal (no_sucursal), FOREIGN KEY (codigo_producto) REFERENCES productos (codigo_producto)); insert into sucursal_productos values (1,1,1651,25,200,20), (2,1,1722,100,800,99), (3,1,1658,480,500,40), (4,1,1321,1000,2000,500), (5,1,8170,5,8,3), (6,2,1651,30,200,20), (7,2,1722,100,800,99), (8,2,1658,300,500,40), (9,2,1321,500,2000,500), (10,2,8170,10,8,3), (11,3,1651,320,200,20), (12,3,1722,123,800,99), (13,3,1658,154,500,40), (14,3,1321,1200,2000,500), (15,3,8170,5,8,3), (16,4,1651,152,200,20), (17,4,1722,785,800,99), (18,4,1658,124,500,40), (19,4,1321,600,2000,500), (20,4,8170,3,8,3), (21,5,1651,154,200,20), (22,5,1722,200,800,99), (23,5,1658,40,500,40), (24,5,1321,530,2000,500), (25,5,8170,4,8,3); CREATE TABLE promociones ( id_promociones INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, causa_promocion VARCHAR(25) NOT NULL, desc_promocion INT(5) NOT NULL, precio_descuento FLOAT NOT NULL, unidad_medida VARCHAR(15) NOT NULL); insert into promociones values (1,"producto con danios",30,73.5,"pza"), (2,"producto menos vendido",15,425,"pza"); CREATE TABLE promocion_prod ( id_promocion_d INT(15) NOT NULL AUTO_INCREMENT PRIMARY KEY, codigo_producto VARCHAR(10) NOT NULL, id_promociones INT(15) NOT NULL, fecha_inicio TIMESTAMP NOT NULL, fecha_final TIMESTAMP NOT NULL, FOREIGN KEY (codigo_producto) REFERENCES productos (codigo_producto), FOREIGN KEY (id_promociones) REFERENCES promociones (id_promociones)); insert into promocion_prod values (1,1651,1,"2018-08-16","2018-10-16"), (2,8170,2,"2018-08-16","2019-01-16"); CREATE TABLE empleados_compras ( RFC_empl_comp CHAR(13) NOT NULL PRIMARY KEY, nombre_empl_comp VARCHAR(25) NOT NULL, ap_pat_comp VARCHAR(25) NOT NULL, ap_mat_comp VARCHAR(25) NOT NULL, sexo_comp VARCHAR(10) NOT NULL, estado_civil_comp VARCHAR(15) NOT NULL, telefono_comp Varchar(12) NOT NULL, correo_comp VARCHAR(30) NOT NULL, usuario_comp VARCHAR(25) NOT NULL, passwd_comp VARCHAR(25) NOT NULL, fecha_ingreso_comp timestamp NOT NULL); insert into empleados_compras values ("BAFJ701213SB1","Juan","Barrios","Fernández","hombre","casado","5557542100","<EMAIL>","barrios69","1234","2018-01-01"), ("MAHM670102N01","Manuel","Martinez","Hernández","hombre","divorciado","5547896332","<EMAIL>","manu15","1234","2018-05-03"), ("RASL75112LM50","<NAME>","Ramirez","Sanchez","mujer","soltero","7755896412","<EMAIL>","mariaR","1234","2018-02-02"), ("ADD7808121G80","Dolores","<NAME>","Davilos","mujer","soltero","7751200145","<EMAIL>","doloresMart","1234","2018-03-15"), ("CALF750228LK7","Felipe","Camargo","Lozano","hombre","soltero","7756632114","<EMAIL>","FelipeC","1234","2018-08-12"); CREATE TABLE proveedores ( id_proveedor INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, nombre_prov VARCHAR(100) NOT NULL, ap_pat_prov VARCHAR(100) NOT NULL, ap_mat_prov VARCHAR(100) NOT NULL, telefono_prov Varchar(12) NOT NULL, calle_prov VARCHAR(100) NOT NULL, colonia_prov VARCHAR(100) NOT NULL, numero_prov INT(15) NOT NULL, provincia_prov VARCHAR(25) NOT NULL, correo_prov VARCHAR(100) NOT NULL); insert into proveedores values ( 1,"Diana","gayosso","octaviano","7751247896","jacarandas","2 de enero",7,"santiago","<EMAIL>"), ( 2,"luisa","octaviano","sebastian","7754120314","girasoles","las rosas",502,"tulancingo","lu<EMAIL>"), ( 3,"<NAME>","octaviano","sebastian","7754012377","<NAME>","5 de mayo",20,"cuautepec","<EMAIL>"), ( 4,"Mario","nieto","lopez","7754100256","tlalpan","rio balsas",536,"mexico","<EMAIL>"), ( 5,"Diego","bolaños","pardo","7757583652","tepeapulco","lindavista",358,"sagun","<EMAIL>"); CREATE TABLE compra ( id_compra INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, id_proveedor INT(5) NOT NULL, fecha_compra timestamp NOT NULL, importe_comp FLOAT NOT NULL, iva_comp FLOAT NOT NULL, subtotal_comp FLOAT NOT NULL, RFC_empleado_comp VARCHAR(25) NOT NULL, no_sucursal INT(5) NOT NULL, FOREIGN KEY (id_proveedor) REFERENCES proveedores (id_proveedor), FOREIGN KEY ( RFC_empleado_comp) REFERENCES empleados_compras (RFC_empl_comp)); insert into compra values (1,2,"2018-05-12",5070,316.88,5386.88,"BAFJ701213SB1",1), (2,1,"2018-03-23",4475,279.69,4754.69,"MAHM670102N01",2), (3,3,"2018-11-01",1440,90.00,1530.00,"RASL75112LM50",3), (4,5,"2018-07-20",3800,237.50,4037.50,"ADD7808121G80",3), (5,4,"2018-10-20",10825,676.56,11501.56,"CALF750228LK7",4); CREATE TABLE detalle_compra( id_detalle_compra int(5) not null AUTO_INCREMENT primary key, id_compra INT(5) NOT NULL, codigo_producto_comp varchar(13) not null, cantidad_comp int(25) not null, precio_comp float not null, total_producto_comp float not null, FOREIGN KEY(id_compra) REFERENCES compra (id_compra), FOREIGN KEY(codigo_producto_comp) REFERENCES productos (codigo_producto)); insert into detalle_compra values (1,1,1651,20,63.5,1270), (2,1,1722,20,15,300), (3,2,1658,10,380,3800), (4,2,1321,15,45,675), (5,3,8170,2,450,900), (6,3,1321,12,45,540), (7,4,1658,10,380,3800), (8,5,1651,100,63.5,6350), (9,5,1658,10,380,3800), (10,5,1321,15,45,675); CREATE TABLE empleados_ventas ( RFC_empl_vent CHAR(13) NOT NULL PRIMARY KEY, nombre_empl_vent VARCHAR(25) NOT NULL, ap_pat_vent VARCHAR(25) NOT NULL, ap_mat_vent VARCHAR(25) NOT NULL, sexo_vent VARCHAR(10) NOT NULL, estado_civil_vent VARCHAR(15) NOT NULL, telefono_vent Varchar(12) NOT NULL, correo_vent VARCHAR(30) NOT NULL, usuario_vent VARCHAR(25) NOT NULL, passwd_vent VARCHAR(100) NOT NULL, fecha_ingreso_vent timestamp NOT NULL); insert into empleados_ventas values ("CAGC800503021","Cinthia","Cazarez","Garcia","mujer","soltero","5575285866","<EMAIL>","cinita_garcia",1234,"2018-02-05"), ("TCHM830304102","Maria","Torres","Hernández","mujer","soltero","7538907451","<EMAIL>","Maria_torres",1234,"2018-03-15"), ("CAJJ790305145","Javier","Carrasco","Jimenez","hombre","soltero","7757536987","<EMAIL>","Javier_carraso",1234,"2018-05-04"), ("RIM8840305102","Benito","Rivera","Martinez","hombre","casado","7757589641","<EMAIL>","Beniro_rivera",1234,"2018-03-20"), ("PIPL850306120","Lilia","Prieto","Perez","mujer","casado","7757541230","<EMAIL>","Lilia_prieto",1234,"2018-01-01"); CREATE TABLE clientes ( RFC_cliente CHAR(13) NOT NULL PRIMARY KEY, nombre_client VARCHAR(25) NOT NULL, ap_pat_client VARCHAR(25) NOT NULL, ap_mat_client VARCHAR(25) NOT NULL, telefono_client VARCHAR(12) NOT NULL, municipio_client VARCHAR(50) NOT NULL, calle_client VARCHAR(50) NOT NULL, colonia_client VARCHAR(50) NOT NULL, numero_client VARCHAR(5) NOT NULL, correo_client VARCHAR(50) NOT NULL, puntos INT NULL); insert into clientes values ("CLIENTEGENERA","cliente_general"," "," "," "," "," "," "," "," ",0), ("HEOI231DFR456","Ivan","Hernandez","Osornio","7757538907","Tulancingo","rio balsas","<NAME>","5","<EMAIL>",50), ("GAOA123EDFR4","Angeles","Gayosso","Octaviano","5575285877","Tulancingo","<NAME>","<NAME>","307","<EMAIL>",200), ("DIRA123DFR56T","Amairani","Diaz","Ramirez","7757583454","Tulancingo","lucerna","pajaritos","15","<EMAIL>",100), ("HERA123DFR456","Alexis","Hernandez","Ramirez","7752145689","Tulancingo","guadalupe","guadalupe","10","<EMAIL>",50); CREATE TABLE descuentos ( codigo_descuento INT(5) NOT NULL PRIMARY KEY, porcentaje INT(5) NOT NULL, cantidad_puntos INT(15) NOT NULL); insert into descuentos values (1,0,0), (2,5,50), (3,10,100), (4,15,200); CREATE TABLE ventas( id_ventas int(15) not null AUTO_INCREMENT primary key, RFC_cliente char(13) not null, fecha_venta timestamp not null, subtotal_venta float not null, iva float not null, importe_vent float not null, num_factura varchar (10) not null, RFC_empleado varchar(25) not null, forma_pago varchar(15) not null, no_sucursal int(5) not null, codigo_descuento int(5) not null, puntos_ganados int(15) not null, FOREIGN KEY(RFC_cliente) REFERENCES clientes (RFC_cliente), FOREIGN KEY(RFC_empleado) REFERENCES empleados_ventas (RFC_empl_vent), FOREIGN KEY(codigo_descuento ) REFERENCES descuentos (codigo_descuento)); insert into ventas values (1,"CLIENTEGENERA","2018-02-10",152.47,8.96875,143.50,"null","CAGC800503021","efectivo",1,1,0), (2,"HEOI231DFR456","2018-05-04",63.75,3.75,60.00,1,"TCHM830304102","efectivo",2,2,10), (3,"GAOA123EDFR4","2018-05-15",451.56,26.5625,425.00,2,"CAJJ790305145","efectivo",4,2,10), (4,"DIRA123DFR56T","2018-06-01",2298.19,135.1875,2163.00,3,"RIM8840305102","efectivo",5,3,10), (5,"HERA123DFR456","2018-07-10",79.69,4.6875,75.00,4,"PIPL850306120","efectivo",3,4,10); CREATE TABLE detalle_ventas ( Id_detalle_venta INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, id_ventas INT(15) NOT NULL, codigo_producto VARCHAR(10) NOT NULL, cantidad INT(15) NOT NULL, precio_venta FLOAT NOT NULL, total_producto FLOAT NOT NULL, FOREIGN KEY (id_ventas) REFERENCES ventas (id_ventas), FOREIGN KEY (Codigo_producto) REFERENCES productos (codigo_producto)); insert into detalle_ventas values (1,1,1651,1,73.5,73.5), (2,1,1722,1,20,20), (3,1,1321,1,50,50), (4,2,1722,3,20,60), (5,3,8170,1,425,425), (6,4,1658,2,309,618), (7,4,1658,5,309,1545), (8,5,1722,5,15,75); <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import conectar_tablas.Database; //llamamos la conexion a la BD para almacen import static conectar_tablas.Database.getConexion; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; /** * * @author Octaviano */ public class ModelAgregarSucursal { DefaultTableModel AgregarSucursal = new DefaultTableModel(); //la variable modelo almacenara los tados de la tabla public DefaultTableModel getModelo_AgregarSucursal() { return AgregarSucursal; } public void setModelo_AgregarSucursal(DefaultTableModel modelo_EmCompras) { this.AgregarSucursal = AgregarSucursal; } public int rec;//Variable que tomara el valor seleccionado en la tabla public int getRec() { return rec; } public void setRec(int rec) { this.rec = rec; } /** * Variables para el metodo de busqueda */ public String[] titulos = {"No_sucursal", "calle", "Colonia", "Numero", "Telefono"}; //columnas de la tabla public String[] getTitulos() { return titulos; } public void setTitulos(String[] titulos) { this.titulos = titulos; } public String[] registros = new String[50]; public String[] getRegistros() { return registros; } public void setRegistros(String[] registros) { this.registros = registros; } public String sql; public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } /** * Variables para el metodo de busqueda */ private TableRowSorter trsFiltro; // sirve para filtar los datos dentro de la tabla public TableRowSorter getTrsFiltro() { return trsFiltro; } public void setTrsFiltro(TableRowSorter trsFiltro) { this.trsFiltro = trsFiltro; } public int columnaABuscar = 0; //solo buscara en la primer columa que pertenece al codigo de producto public String cadena; public String getCadena() { return cadena; } public void setCadena(String cadena) { this.cadena = cadena; } public int getColumnaABuscar() { return columnaABuscar; } public void setColumnaABuscar(int columnaABuscar) { this.columnaABuscar = columnaABuscar; } //Variables que corresponden a cada caja de texto private int verificar; private String no_sucursal; private String calle; private String colonia; private String numero; private String telefono; public DefaultTableModel getAgregarSucursal() { return AgregarSucursal; } public void setAgregarSucursal(DefaultTableModel modelo_proveedores) { this.AgregarSucursal = AgregarSucursal; } public int getVerificar() { return verificar; } public void setVerificar(int verificar) { this.verificar = verificar; } public String getNo_sucursal() { return no_sucursal; } public void setNo_sucursal(String no_sucursal) { this.no_sucursal = no_sucursal; } public String getCalle() { return calle; } public void setCalle(String calle) { this.calle = calle; } public String getColonia() { return colonia; } public void setColonia(String colonia) { this.colonia = colonia; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } private Connection conexion; private Statement st; private ResultSet rs; PreparedStatement ps; public Connection getConexion() { return conexion; } public void setConexion(Connection conexion) { this.conexion = conexion; } public Statement getSt() { return st; } public void setSt(Statement st) { this.st = st; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public PreparedStatement getPs() { return ps; } public void setPs(PreparedStatement ps) { this.ps = ps; } DefaultTableModel model; // variable que usa para el metodo de buscar public DefaultTableModel getModel() { return model; } public void setModel(DefaultTableModel model) { this.model = model; } public String Limpiar = " "; // variables para boton limpiar public int codigo = 0; public int cantidad = 0; public int getCantidad() { return cantidad; } public String getLimpiar() { return Limpiar; } public void setLimpiar(String Limpiar) { this.Limpiar = Limpiar; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } private DefaultTableModel model_AgregarSucursal = new DefaultTableModel(); // variable que usa para el metodo de buscar public DefaultTableModel getModel_AgregarSucursal() { return model_AgregarSucursal; } public void setModel_AgregarSucursal(DefaultTableModel model_prov) { this.model_AgregarSucursal = model_prov; } /** * se hace la conexion a la Base de datos y se hace la consulta hacia la * tabla de EmpleadosCompras que tiene una union con la tabla de compra * */ public void Conectar() { try { conexion =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia","root",""); //conexion = DriverManager.getConnection("jdbc:mysql://raspberry-tic41.zapto.org:3306/StockCia", "tic41", "tic41"); st = conexion.createStatement(); rs = st.executeQuery("SELECT * FROM sucursal;"); rs.first(); } catch (SQLException err) { JOptionPane.showMessageDialog(null, "Error " + err.getMessage()); } } public void Guardar_Nuevo() { //cada variable obtendra el valor actual de las cajas de texto no_sucursal = this.getNo_sucursal(); calle = this.getCalle(); colonia = this.getColonia(); numero = this.getNumero(); telefono = this.getTelefono(); int confirmar = JOptionPane.showConfirmDialog(null, "¿Esta seguro de Guardar el NUEVO registro?"); if (JOptionPane.OK_OPTION == confirmar) { try { st.executeUpdate("insert into sucursal (calle, colonia, numero, telefono) values" + "('" + calle + "','" + colonia + "','" + numero + "','" + telefono + "');"); JOptionPane.showMessageDialog(null, "Guardado con exito "); } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error Nuevo no se puede guardar " + err.getMessage()); } } } public void Guardar_Modificado() { no_sucursal = this.getNo_sucursal(); calle = this.getCalle(); colonia = this.getColonia(); numero = this.getNumero(); telefono = this.getTelefono(); int confirmar = JOptionPane.showConfirmDialog(null, "¿Esta seguro de MODIFICAR registro?"); if (JOptionPane.OK_OPTION == confirmar) { try { st.executeUpdate("UPDATE sucursal SET calle='" + calle + "',colonia='" + colonia + "',numero='" + numero + "' ,telefono='" + telefono + "'WHERE no_sucursal='" + no_sucursal + "';"); JOptionPane.showMessageDialog(null, "El registro se modifico correctamente"); } catch (Exception err) { JOptionPane.showMessageDialog(null, "Error Nuevo no se puede guardar " + err.getMessage()); } } } //Metodo mostar public void mostrar() { ResultSet rs = Database.getTabla("SELECT * FROM sucursal;"); AgregarSucursal.setColumnIdentifiers(new Object[]{"no_sucursal", "calle", "Colonia", "Numero", "telefono"}); try { while (rs.next()) { // añade los resultado a al modelo de tabla AgregarSucursal.addRow(new Object[]{ rs.getString("no_sucursal"), rs.getString("calle"), rs.getString("colonia"), rs.getString("numero"), rs.getString("telefono")}); } } catch (Exception e) { System.out.println(e); } } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package views; /** * * @author Octaviano */ public class ViewDescuentos extends javax.swing.JPanel { /** * Creates new form ViewAgregarSucursal */ public ViewDescuentos() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jp_titulo = new javax.swing.JPanel(); jl_titulo = new javax.swing.JLabel(); jp_datos = new javax.swing.JPanel(); jl_no_sucursal = new javax.swing.JLabel(); jtf_codigo_descuento = new javax.swing.JTextField(); jtf_cantidad_puntos = new javax.swing.JTextField(); jtf_porcentaje = new javax.swing.JTextField(); jl_porcentaje = new javax.swing.JLabel(); jl_cantidad_puntos = new javax.swing.JLabel(); jl_buscar = new javax.swing.JLabel(); jtf_buscar = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jt_vista = new javax.swing.JTable(); jp_botones = new javax.swing.JPanel(); jb_nuevo = new javax.swing.JButton(); jl_nuevo = new javax.swing.JLabel(); jb_modificar = new javax.swing.JButton(); jl_modificar = new javax.swing.JLabel(); jb_eliminar = new javax.swing.JButton(); jl_eliminar = new javax.swing.JLabel(); jb_guardar = new javax.swing.JButton(); jl_guadar = new javax.swing.JLabel(); setBackground(new java.awt.Color(255, 255, 255)); setRequestFocusEnabled(false); jp_titulo.setBackground(new java.awt.Color(153, 204, 255)); jl_titulo.setFont(new java.awt.Font("Segoe UI", 0, 50)); // NOI18N jl_titulo.setForeground(new java.awt.Color(102, 102, 102)); jl_titulo.setText("Descuentos"); javax.swing.GroupLayout jp_tituloLayout = new javax.swing.GroupLayout(jp_titulo); jp_titulo.setLayout(jp_tituloLayout); jp_tituloLayout.setHorizontalGroup( jp_tituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_tituloLayout.createSequentialGroup() .addContainerGap() .addComponent(jl_titulo) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_tituloLayout.setVerticalGroup( jp_tituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_titulo) ); jp_datos.setBackground(new java.awt.Color(255, 255, 255)); jp_datos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 0, 14), new java.awt.Color(0, 153, 255))); // NOI18N jl_no_sucursal.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_no_sucursal.setForeground(new java.awt.Color(51, 51, 51)); jl_no_sucursal.setText("codigo_descuento:"); jl_porcentaje.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_porcentaje.setForeground(new java.awt.Color(51, 51, 51)); jl_porcentaje.setText("Porcentaje:"); jl_cantidad_puntos.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N jl_cantidad_puntos.setForeground(new java.awt.Color(51, 51, 51)); jl_cantidad_puntos.setText("cantidad de puntos:"); javax.swing.GroupLayout jp_datosLayout = new javax.swing.GroupLayout(jp_datos); jp_datos.setLayout(jp_datosLayout); jp_datosLayout.setHorizontalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_datosLayout.createSequentialGroup() .addContainerGap(55, Short.MAX_VALUE) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtf_porcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addComponent(jl_cantidad_puntos) .addGap(196, 196, 196)) .addComponent(jtf_cantidad_puntos, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jp_datosLayout.createSequentialGroup() .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jl_porcentaje) .addComponent(jl_no_sucursal)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtf_codigo_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(25, 25, 25)) ); jp_datosLayout.setVerticalGroup( jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_datosLayout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jl_no_sucursal) .addComponent(jtf_codigo_descuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_porcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_porcentaje)) .addGap(27, 27, 27) .addGroup(jp_datosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jtf_cantidad_puntos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_cantidad_puntos)) .addContainerGap(45, Short.MAX_VALUE)) ); jl_buscar.setFont(new java.awt.Font("Segoe UI", 0, 12)); // NOI18N jl_buscar.setForeground(new java.awt.Color(102, 153, 255)); jl_buscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/buscar .png"))); // NOI18N jl_buscar.setText("buscar por codigo de descuento:"); jt_vista.setFont(new java.awt.Font("Segoe UI", 0, 11)); // NOI18N jt_vista.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "codigo de descuento", "porcentaje", "cantidad de puntos" } )); jScrollPane1.setViewportView(jt_vista); jp_botones.setBackground(new java.awt.Color(255, 255, 51)); jb_nuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/nuevo.png"))); // NOI18N jl_nuevo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_nuevo.setForeground(new java.awt.Color(51, 51, 51)); jl_nuevo.setText("Nuevo"); jb_modificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Modificar.png"))); // NOI18N jl_modificar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_modificar.setForeground(new java.awt.Color(51, 51, 51)); jl_modificar.setText("Modificar"); jb_eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/eliminar.png"))); // NOI18N jl_eliminar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_eliminar.setForeground(new java.awt.Color(51, 51, 51)); jl_eliminar.setText("Eliminar"); jb_guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/Guardar.png"))); // NOI18N jb_guardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jb_guardarActionPerformed(evt); } }); jl_guadar.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N jl_guadar.setForeground(new java.awt.Color(51, 51, 51)); jl_guadar.setText("Guardar"); javax.swing.GroupLayout jp_botonesLayout = new javax.swing.GroupLayout(jp_botones); jp_botones.setLayout(jp_botonesLayout); jp_botonesLayout.setHorizontalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_botonesLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jl_nuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(68, 68, 68) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_modificar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_modificar)) .addGap(195, 195, 195)) .addGroup(jp_botonesLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_guadar)) .addGap(59, 59, 59) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_eliminar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jp_botonesLayout.setVerticalGroup( jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addContainerGap() .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jb_nuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jb_modificar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jl_modificar) .addComponent(jl_nuevo)) .addGap(18, 18, Short.MAX_VALUE) .addGroup(jp_botonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jp_botonesLayout.createSequentialGroup() .addComponent(jb_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jl_eliminar)) .addGroup(jp_botonesLayout.createSequentialGroup() .addGap(72, 72, 72) .addComponent(jl_guadar)) .addComponent(jb_guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE))) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jp_titulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 597, Short.MAX_VALUE) .addComponent(jl_buscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(79, 79, 79))) .addComponent(jScrollPane1))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jp_titulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jl_buscar)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jScrollPane1)) .addGroup(layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jp_datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(32, 32, 32) .addComponent(jp_botones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(35, 35, 35)) ); }// </editor-fold>//GEN-END:initComponents private void jb_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_guardarActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jb_guardarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JScrollPane jScrollPane1; public javax.swing.JButton jb_eliminar; public javax.swing.JButton jb_guardar; public javax.swing.JButton jb_modificar; public javax.swing.JButton jb_nuevo; private javax.swing.JLabel jl_buscar; public javax.swing.JLabel jl_cantidad_puntos; public javax.swing.JLabel jl_eliminar; public javax.swing.JLabel jl_guadar; public javax.swing.JLabel jl_modificar; public javax.swing.JLabel jl_no_sucursal; public javax.swing.JLabel jl_nuevo; public javax.swing.JLabel jl_porcentaje; public javax.swing.JLabel jl_titulo; public javax.swing.JPanel jp_botones; public javax.swing.JPanel jp_datos; private javax.swing.JPanel jp_titulo; public javax.swing.JTable jt_vista; public javax.swing.JTextField jtf_buscar; public javax.swing.JTextField jtf_cantidad_puntos; public javax.swing.JTextField jtf_codigo_descuento; public javax.swing.JTextField jtf_porcentaje; // End of variables declaration//GEN-END:variables } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controllers; import models.ModelAgregarSucursal; import views.ViewAgregarSucursal; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; /** * * @author Octaviano */ public class ControllerAgregarSucursal { ModelAgregarSucursal modelAgregarSucursal; ViewAgregarSucursal viewAgregarSucursal; ActionListener list = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewAgregarSucursal.jb_nuevo) { nuevo_AgregarSucursal(); } else if (e.getSource() == viewAgregarSucursal.jb_modificar) { modificar_AgregarSucursal(); } else if (e.getSource() == viewAgregarSucursal.jb_guardar) { GuardarAgregarSucursal(); } } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewAgregarSucursal.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }; /** * Busar solo con un compo, no es necesario el metodo de filtro toda la * accion de buscar esta dentro del evento keyListener */ KeyListener key = new KeyListener() { @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewAgregarSucursal.jtf_buscar) { modelAgregarSucursal.setTrsFiltro(new TableRowSorter(viewAgregarSucursal.jt_vista.getModel())); viewAgregarSucursal.jt_vista.setRowSorter(modelAgregarSucursal.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { modelAgregarSucursal.setCadena(viewAgregarSucursal.jtf_buscar.getText()); viewAgregarSucursal.jtf_buscar.setText(modelAgregarSucursal.getCadena()); modelAgregarSucursal.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewAgregarSucursal.jtf_buscar.getText(), modelAgregarSucursal.getColumnaABuscar())); } }; public ControllerAgregarSucursal(ModelAgregarSucursal modelAgregarSucursal, ViewAgregarSucursal viewAgregarSucursal) { this.modelAgregarSucursal = modelAgregarSucursal; this.viewAgregarSucursal = viewAgregarSucursal; this.viewAgregarSucursal.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la caja e texto buscar this.viewAgregarSucursal.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener viewAgregarSucursal.jb_guardar.setEnabled(false); //El boton guardar aparecera inhabilitado viewAgregarSucursal.jb_eliminar.setEnabled(false); //El boton guardar aparecera inhabilitado cajas_deshabilitadas(); setActionListener(); ConexionBD(); } private void setActionListener() { viewAgregarSucursal.jb_nuevo.addActionListener(list); viewAgregarSucursal.jb_modificar.addActionListener(list); viewAgregarSucursal.jb_guardar.addActionListener(list); } public void ConexionBD() { modelAgregarSucursal.Conectar(); modelAgregarSucursal.mostrar(); viewAgregarSucursal.jt_vista.setModel(modelAgregarSucursal.getModelo_AgregarSucursal()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked() { viewAgregarSucursal.jb_guardar.setEnabled(false); viewAgregarSucursal.jb_modificar.setEnabled(true);//El boton modificar aparecera habilitado viewAgregarSucursal.jb_nuevo.setEnabled(true);//El boton nuevo aparecera habilitado cajas_deshabilitadas(); // cuando se haga clic en la tabla, las cajas se volveran a deshabilitar modelAgregarSucursal.setRec(viewAgregarSucursal.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewAgregarSucursal.jtf_no_sucursal.setText(viewAgregarSucursal.jt_vista.getValueAt(modelAgregarSucursal.getRec(), 0).toString()); viewAgregarSucursal.jtf_calle.setText(viewAgregarSucursal.jt_vista.getValueAt(modelAgregarSucursal.getRec(), 1).toString()); viewAgregarSucursal.jtf_colonia.setText(viewAgregarSucursal.jt_vista.getValueAt(modelAgregarSucursal.getRec(), 2).toString()); viewAgregarSucursal.jtf_numero.setText(viewAgregarSucursal.jt_vista.getValueAt(modelAgregarSucursal.getRec(), 3).toString()); viewAgregarSucursal.jtf_telefono.setText(viewAgregarSucursal.jt_vista.getValueAt(modelAgregarSucursal.getRec(), 4).toString()); } private void cajas_deshabilitadas() { viewAgregarSucursal.jtf_no_sucursal.setEditable(false); viewAgregarSucursal.jtf_calle.setEditable(false); viewAgregarSucursal.jtf_colonia.setEditable(false); viewAgregarSucursal.jtf_numero.setEditable(false); viewAgregarSucursal.jtf_telefono.setEditable(false); } private void cajas_habilitadas() { viewAgregarSucursal.jtf_calle.setEditable(true); viewAgregarSucursal.jtf_colonia.setEditable(true); viewAgregarSucursal.jtf_numero.setEditable(true); viewAgregarSucursal.jtf_telefono.setEditable(true); } public void nuevo_AgregarSucursal() { viewAgregarSucursal.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewAgregarSucursal.jb_modificar.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelAgregarSucursal.setVerificar(1);// le da el valor a verificar de cero para identificar un nuevo registro viewAgregarSucursal.jtf_no_sucursal.setText(modelAgregarSucursal.getLimpiar()); viewAgregarSucursal.jtf_calle.setText(modelAgregarSucursal.getLimpiar()); viewAgregarSucursal.jtf_colonia.setText(modelAgregarSucursal.getLimpiar()); viewAgregarSucursal.jtf_numero.setText(modelAgregarSucursal.getLimpiar()); viewAgregarSucursal.jtf_telefono.setText(modelAgregarSucursal.getLimpiar()); cajas_habilitadas();//llamar al metodo de cajas habilitadas para proceder a escribir un nuevo registro } public void modificar_AgregarSucursal() { viewAgregarSucursal.jb_guardar.setEnabled(true);//El boton guardar aparecera habilitado viewAgregarSucursal.jb_nuevo.setEnabled(false);//El boton modificar aparecera inhabilitado //limpiar cada caja de la Interfaz modelAgregarSucursal.setVerificar(2);// le da el valor a verificar de uno para identificar Modifiar registro viewAgregarSucursal.jtf_no_sucursal.setEditable(false); // el codigo no se puede modificar viewAgregarSucursal.jtf_calle.setEditable(true); viewAgregarSucursal.jtf_colonia.setEditable(true); viewAgregarSucursal.jtf_numero.setEditable(true); viewAgregarSucursal.jtf_telefono.setEditable(true); } public void GuardarAgregarSucursal() { // si la variable verificar es igual a 0 se llama al metodo de guardar Nuevo if (modelAgregarSucursal.getVerificar() == 1) { // darle el valor a las variables modelAgregarSucursal.setNo_sucursal(viewAgregarSucursal.jtf_no_sucursal.getText()); modelAgregarSucursal.setCalle(viewAgregarSucursal.jtf_calle.getText()); modelAgregarSucursal.setColonia(viewAgregarSucursal.jtf_colonia.getText()); modelAgregarSucursal.setNumero(viewAgregarSucursal.jtf_numero.getText()); modelAgregarSucursal.setTelefono(viewAgregarSucursal.jtf_telefono.getText()); modelAgregarSucursal.Guardar_Nuevo(); // metodo de insertar nuevo registro } else { // darle el valor a las variables modelAgregarSucursal.setNo_sucursal(viewAgregarSucursal.jtf_no_sucursal.getText()); modelAgregarSucursal.setCalle(viewAgregarSucursal.jtf_calle.getText()); modelAgregarSucursal.setColonia(viewAgregarSucursal.jtf_colonia.getText()); modelAgregarSucursal.setNumero(viewAgregarSucursal.jtf_numero.getText()); modelAgregarSucursal.setTelefono(viewAgregarSucursal.jtf_telefono.getText()); modelAgregarSucursal.Guardar_Modificado(); } //LIMPIAR TABLA for (int i = 0; i < viewAgregarSucursal.jt_vista.getRowCount(); i++) { modelAgregarSucursal.getModelo_AgregarSucursal().removeRow(i); i -= 1; } //mostrar los nuevos datos modelAgregarSucursal.mostrar(); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package models; import conectar_tablas.Database; //llamamos la conexion a la BD para almacen import static conectar_tablas.Database.getConexion; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; /** * * @author Octaviano */ public class ModelPromociones { DefaultTableModel modelo_promocion = new DefaultTableModel(); //la variable modelo almacenara los tados de la tabla public DefaultTableModel getModelo_promocion() { return modelo_promocion; } public void setModelo_promocion(DefaultTableModel modelo_promocion) { this.modelo_promocion = modelo_promocion; } public int rec;//Variable que tomara el valor seleccionado en la tabla public int getRec() { return rec; } public void setRec(int rec) { this.rec = rec; } public String[] titulos = {"No promocion", "Causa", "Descuento", "precio_descuento", "unidad de medida", "codigo del producto", "fecha_inicio", "fecha_final"}; //columnas de la tabla public String[] getTitulos() { return titulos; } public void setTitulos(String[] titulos) { this.titulos = titulos; } public String[] registros = new String[50]; public String[] getRegistros() { return registros; } public void setRegistros(String[] registros) { this.registros = registros; } public String sql; public String getSql() { return sql; } public void setSql(String sql) { this.sql = sql; } /** * Variables para el metodo de busqueda */ private TableRowSorter trsFiltro; // sirve para filtar los datos dentro de la tabla public TableRowSorter getTrsFiltro() { return trsFiltro; } public void setTrsFiltro(TableRowSorter trsFiltro) { this.trsFiltro = trsFiltro; } public int columnaABuscar; public String cadena; public String getCadena() { return cadena; } public void setCadena(String cadena) { this.cadena = cadena; } public int getColumnaABuscar() { return columnaABuscar; } public void setColumnaABuscar(int columnaABuscar) { this.columnaABuscar = columnaABuscar; } private int verificar; private ArrayList producto; private String no_promocion; private String causa; private String descuento; private String precion_descuento; private String unidad_medida; private String codigo_producto; private String fecha_inicio; private String fecha_final; private String nombre_producto;// solo se obtendra este dato, no se almacenara private String precio_unitario_venta;// solo se obtendra este dato, no se almacenara private String marca_producto;// solo se obtendra este dato, no se almacenara public int getVerificar() { return verificar; } public void setVerificar(int verificar) { this.verificar = verificar; } public String getNo_promocion() { return no_promocion; } public void setNo_promocion(String no_promocion) { this.no_promocion = no_promocion; } public String getCausa() { return causa; } public void setCausa(String causa) { this.causa = causa; } public String getDescuento() { return descuento; } public void setDescuento(String descuento) { this.descuento = descuento; } public String getPrecion_descuento() { return precion_descuento; } public void setPrecion_descuento(String precion_descuento) { this.precion_descuento = precion_descuento; } public String getUnidad_medida() { return unidad_medida; } public String getCodigo_producto() { return codigo_producto; } public void setCodigo_producto(String codigo_producto) { this.codigo_producto = codigo_producto; } public String getPrecio_unitario_venta() { return precio_unitario_venta; } public void setPrecio_unitario_venta(String precio_unitario_venta) { this.precio_unitario_venta = precio_unitario_venta; } public String getMarca_producto() { return marca_producto; } public void setMarca_producto(String marca_producto) { this.marca_producto = marca_producto; } public ArrayList getProducto() { return producto; } public void setProducto(ArrayList producto) { this.producto = producto; } public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public String getFecha_inicio() { return fecha_inicio; } public void setFecha_inicio(String fecha_inicio) { this.fecha_inicio = fecha_inicio; } public String getFecha_final() { return fecha_final; } public void setFecha_final(String fecha_final) { this.fecha_final = fecha_final; } public String Limpiar = " "; public int codigo = 0; public String getLimpiar() { return Limpiar; } public void setLimpiar(String Limpiar) { this.Limpiar = Limpiar; } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } DefaultTableModel model = new DefaultTableModel(); // variable que usa para el metodo de buscar public DefaultTableModel getModel() { return model; } public void setModel(DefaultTableModel model) { this.model = model; } private Connection conexion; private Statement st; private ResultSet rs; PreparedStatement ps; public void Conectar() { try { conexion =DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia","root",""); //conexion = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3307/stockcia", "root", ""); st = conexion.createStatement(); rs = st.executeQuery("SELECT promociones.id_promociones,causa_promocion, desc_promocion,precio_descuento, promociones.unidad_medida, promocion_prod.codigo_producto, promocion_prod.fecha_inicio, promocion_prod.fecha_final from promociones inner join promocion_prod on promociones.id_promociones = promocion_prod.id_promociones;"); rs.first(); } catch (SQLException err) { JOptionPane.showMessageDialog(null, "Error " + err.getMessage()); } } /////////////////////////////////////////////////////////////// public void llenarCombo() { ArrayList codigo = new ArrayList(); try { rs = st.executeQuery("SELECT * FROM productos;"); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "error4 al llenar comboBox" + e); } try { while (rs.next()) { String sucursal = rs.getString("codigo_producto"); codigo.add(sucursal);//agregar los datos a la lista } this.setProducto(codigo);// almacena la lista con los numeros de proveedores obetenidos de la BD } catch (Exception e) { JOptionPane.showMessageDialog(null, "error5 al llenar comboBox" + e); } } public void llenarTextFieldsProductos() { try { codigo_producto = this.getCodigo_producto(); rs = st.executeQuery("SELECT * FROM productos WHERE codigo_producto='" + codigo_producto + "';");//consulta a empleaddos compras rs.next(); nombre_producto = rs.getString("nom_producto"); marca_producto = rs.getString("marca"); precio_unitario_venta = rs.getString("precio_unitario_venta"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "error8 al llenarTextFields" + e); } } //////////////////////////////////////////// public void mostrar() { ResultSet rs = Database.getTabla("SELECT promociones.id_promociones,causa_promocion, desc_promocion,precio_descuento, promociones.unidad_medida, promocion_prod.codigo_producto, promocion_prod.fecha_inicio, promocion_prod.fecha_final from promociones inner join promocion_prod on promociones.id_promociones = promocion_prod.id_promociones;"); modelo_promocion.setColumnIdentifiers(new Object[]{"No promocion", "Causa", "Descuento", "precio_descuento", "unidad de medida", "codigo del producto", "fecha_inicio", "fecha_final"}); try { while (rs.next()) { // añade los resultado a al modelo de tabla modelo_promocion.addRow(new Object[]{rs.getString("promociones.id_promociones"), rs.getString("causa_promocion"), rs.getString("desc_promocion"), rs.getString("precio_descuento"), rs.getString("unidad_medida"), rs.getString("codigo_producto"), rs.getString("fecha_inicio"), rs.getString("fecha_final")}); } } catch (Exception e) { System.out.println(e); } } } <file_sep>package controllers; import models.ModelPromociones; import views.ViewPromociones; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JOptionPane; import javax.swing.RowFilter; import javax.swing.table.TableRowSorter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author LAB-1 */ public class ControllerPromociones { ModelPromociones modelPromociones; ViewPromociones viewPromociones; ActionListener list = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == viewPromociones.jcb_codigo_producto) { modelPromociones.setCodigo_producto((String) viewPromociones.jcb_codigo_producto.getSelectedItem()); modelPromociones.llenarTextFieldsProductos(); viewPromociones.jtf_nombre_producto.setText(modelPromociones.getNombre_producto()); viewPromociones.jtf_tipo_producto.setText(modelPromociones.getPrecio_unitario_venta()); viewPromociones.jtf_marca_producto.setText(modelPromociones.getMarca_producto()); //habilitar cajas de texto } } }; MouseListener ml = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getSource() == viewPromociones.jt_vista) { jt_vista_MouseClicked(); } } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }; KeyListener key = new KeyListener() { @Override public void keyTyped(KeyEvent e) { if (e.getSource() == viewPromociones.jtf_buscar) { modelPromociones.setTrsFiltro(new TableRowSorter(viewPromociones.jt_vista.getModel())); viewPromociones.jt_vista.setRowSorter(modelPromociones.getTrsFiltro()); } } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if (e.getSource() == viewPromociones.jtf_buscar) { modelPromociones.setCadena(viewPromociones.jtf_buscar.getText()); viewPromociones.jtf_buscar.setText(modelPromociones.getCadena()); modelPromociones.getTrsFiltro().setRowFilter(RowFilter.regexFilter(viewPromociones.jtf_buscar.getText(), modelPromociones.getColumnaABuscar())); } } }; public ControllerPromociones(ModelPromociones modelPromociones, ViewPromociones viewPromociones) { this.modelPromociones = modelPromociones; this.viewPromociones = viewPromociones; this.viewPromociones.jt_vista.addMouseListener(ml);//agregar a la table el evento de MouseListener this.viewPromociones.jtf_buscar.addKeyListener(key); //agregar elevento de keylistener en la tabla ConexionBD(); modelPromociones.Conectar();// conexion a la BD initComponents(); llenadoCombos(); setActionListener(); } public void llenadoCombos() { modelPromociones.llenarCombo(); for (int c = 0; c < modelPromociones.getProducto().size(); c++) { viewPromociones.jcb_codigo_producto.addItem((String) modelPromociones.getProducto().get(c)); } } public void setActionListener() { viewPromociones.jcb_codigo_producto.addActionListener(list); } public void initComponents() { viewPromociones.jcb_codigo_producto.removeAllItems(); } // public void ConexionBD() { modelPromociones.Conectar(); modelPromociones.mostrar(); viewPromociones.jt_vista.setModel(modelPromociones.getModelo_promocion()); //asignar a la tabla los valores correspondientes } public void jt_vista_MouseClicked() { modelPromociones.setRec(viewPromociones.jt_vista.getSelectedRow());//a la variable se le asigna el elemento seleccionado en la tabla viewPromociones.jtf_no_promocion.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 0).toString()); viewPromociones.jtf_causa.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 1).toString()); viewPromociones.jtf_colonia1.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 2).toString()); viewPromociones.jtf_numero1.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 3).toString()); viewPromociones.jtf_telefono1.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 4).toString()); // viewPromociones.jtf_no_sucursal.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 5).toString()); //viewPromociones.jtf_calle.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 6).toString()); //viewPromociones.jtf_colonia.setText(viewPromociones.jt_vista.getValueAt(modelPromociones.getRec(), 7).toString()); } }
fc9e555a2e155af867af1b4db9fe6ddff6cb132c
[ "Java", "SQL" ]
27
Java
CIA-Developers/StockCia
23991b218ab95496118c402a13bf98c80269f785
01c97a6ad1b64ecb8c7dae6ed70405bafa104b02
refs/heads/master
<file_sep># ionic-tuts <file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { AdMobFree, AdMobFreeBannerConfig, AdMobFreeInterstitialConfig, AdMobFreeRewardVideoConfig } from '@ionic-native/admob-free'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { constructor(public navCtrl: NavController, private admobFree: AdMobFree) {} // ionViewDidLoad should start the banner ad as soon as the app is ready ionViewDidLoad() { const bannerConfig: AdMobFreeBannerConfig = { id: '', isTesting: false, autoShow: true }; this.admobFree.banner.config(bannerConfig); this.admobFree.banner.prepare() .then(() => { // banner Ad is ready // if we set autoShow to false, then we will need to call the show method here }) .catch(e => console.log(e)); } showBanner() { const bannerConfig: AdMobFreeBannerConfig = { id: '', isTesting: false, autoShow: true }; this.admobFree.banner.config(bannerConfig); this.admobFree.banner.prepare() .then(() => { // banner Ad is ready // if we set autoShow to false, then we will need to call the show method here }) .catch(e => console.log(e)); } showInterstitial() { const interstitialConfig: AdMobFreeInterstitialConfig = { id: '', isTesting: false, autoShow: true }; this.admobFree.interstitial.config(interstitialConfig); this.admobFree.interstitial.prepare() .then(() => { // banner Ad is ready // if we set autoShow to false, then we will need to call the show method here }) .catch(e => console.log(e)); } showRewarded() { const rewardVideoConfig: AdMobFreeRewardVideoConfig = { id: '', isTesting: false, autoShow: true }; this.admobFree.rewardVideo.config(rewardVideoConfig); this.admobFree.rewardVideo.prepare() .then(() => { // banner Ad is ready // if we set autoShow to false, then we will need to call the show method here }) .catch(e => console.log(e)); } } <file_sep>Based on this this references: 1. https://ionicframework.com/docs/native/admob-free/ 2. https://www.youtube.com/watch?v=4wXSAtSc0go 3. https://www.youtube.com/watch?v=Woq8c9IghZo Firebase(not added): tutorial here: https://github.com/angular/angularfire2/blob/master/docs/ionic/v3.md
4d5442ff9a0e7fdf3a423fc9c91885e59717024a
[ "Markdown", "TypeScript" ]
3
Markdown
alexdobsom/ionic-tuts
73527d45d3e7aac8de43f0d1ae78cbe877dce87e
11725cd75c8d4cb5e48244ebda20ea1a4fe33f55
refs/heads/master
<file_sep>ecdsa==0.13 pip==7.1.0<file_sep>from typing import List from decorators import singleton from exceptions import WrongTransactionException from input import AbstractInput from output import AbstractOutput class AbstractTransaction(object): @property def txid(self) -> str: raise NotImplementedError() @singleton class StartTransaction(AbstractTransaction): def __init__(self, outputs: List[AbstractOutput], version: int = 0) -> None: if len(outputs) == 0: raise WrongTransactionException("Start transaction should have at least one output") self.__version = version self.__outputs = outputs @property def txid(self) -> str: return "" class Transaction(AbstractTransaction): def __init__(self, inputs: List[AbstractInput], outputs: List[AbstractOutput], version: int = 0) -> None: if len(inputs) == 0: raise WrongTransactionException("Transaction should have at least one input") if len(outputs) == 0: raise WrongTransactionException("Transaction should have at least one output") self.__version = version self.__inputs = inputs self.__outputs = outputs @property def txid(self) -> str: return "" <file_sep>class BlockChainException(Exception): message = "Internal error in blockchain element" class UselessBlockException(BlockChainException): message = "Creating of useless block (without transactions)" class TransactionException(Exception): message = "Internal error in transaction element" class WrongTransactionException(TransactionException): message = "Invalid transaction initiation" class WrongOutputValueException(TransactionException): message = "Wrong output value for transaction (should be more than 0)" <file_sep>from typing import List from random import randint from decorators import singleton from exceptions import UselessBlockException from transaction import AbstractTransaction from utils import get_hash class AbstractBlock(object): def get_header_hash(self) -> str: raise NotImplementedError() @singleton class StartBlock(AbstractBlock): def __init__(self, transactions: List[AbstractTransaction]) -> None: self.chain_seed = str(randint(0, 1000000000)) self.__transactions = transactions def get_header_hash(self) -> str: return get_hash(self.chain_seed) class Block(AbstractBlock): __transactions = [] __previous_block_hash = None def __init__(self, previous_block: AbstractBlock, transactions: List[AbstractTransaction]) -> None: if len(transactions) == 0: raise UselessBlockException() self.__transactions = transactions self.__previous_block_hash = previous_block.get_header_hash() @property def __merkle_root(self) -> str: def __do_iteration(data: List[str]) -> str: new_data = [] len_data = len(data) for i in range(0, len_data, 2): row = data[i] if (i + 1) == len_data: row += data[i] else: row += data[i + 1] new_data.append(get_hash(row)) if len(new_data) == 1: return new_data[0] return __do_iteration(new_data) return __do_iteration([el.txid for el in self.__transactions]) def get_header_hash(self) -> str: return get_hash(self.__previous_block_hash + self.__merkle_root) <file_sep>from exceptions import WrongOutputValueException class AbstractOutput(object): pass class Output(AbstractOutput): def __init__(self, value: float, script_pub_sig: str) -> None: if value <= 0: raise WrongOutputValueException() self.__value = value self.__script_pub_sig = script_pub_sig <file_sep>class AbstractInput(object): pass class Input(AbstractInput): def __init__(self, previous_txid, output_index, script_sig): self.__previous_txid = previous_txid self.__output_index = output_index self.__script_sig = script_sig <file_sep>import hashlib def get_hash(row: str) -> bytes: return hashlib.sha256(row.encode("utf-8")).digest() <file_sep>from block import StartBlock from output import Output from transaction import StartTransaction from wallet import Wallet start_wallet = Wallet() start_wallet.save("private.pem", "public.pem") start_output = Output(100, start_wallet.public_key) start_transaction = StartTransaction(outputs=[start_output]) start_block = StartBlock(transactions=[start_transaction]) <file_sep>from ecdsa import SECP256k1, SigningKey from pip.utils import cached_property class AbstractWallet(object): pass class Wallet(AbstractWallet): def __init__(self, private_string: str = None) -> None: if private_string is not None: self.__signing_key = SigningKey.from_string(private_string, curve=SECP256k1, hashfunc='sha256') else: self.__signing_key = SigningKey.generate(curve=SECP256k1, hashfunc='sha256') self.__verification_key = self.__signing_key.get_verifying_key() @cached_property def public_key(self) -> str: return self.__verification_key.to_pem() @cached_property def private_key(self) -> str: return self.__signing_key.to_pem() def save(self, private_path: str, public_path: str) -> None: open(private_path, "wb").write(self.private_key) open(public_path, "wb").write(self.public_key)
e79ad33ec955bb3c34a47f18c98d60cf16ee9faa
[ "Python", "Text" ]
9
Text
kazmiruk/blockchain-test
9d6c261366b7c26806a0b51d601bf71486633a89
5a1da4e6381c469b051cf88de74030436e5be539